Ifstream读取错误 [英] Ifstream reading error

查看:123
本文介绍了Ifstream读取错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用ifstream读取bmp文件,但是无需调试即可正常运行,当我在调试模式下运行它时会失败.开始时,我读取了54个字节的信息,以获取图片的高度和宽度,不幸的是,在调试模式下,图片的高度和宽度为-858993460,因此每次图片的整个大小都会溢出,因此会出现严重的分配错误.我使用VS 2013,有人可以帮我吗?

I have been trying to read a bmp file with ifstream, however it works fine without debugging, when I run it in debug mode it fails. At the beginning I read 54 bytes of info, to get the height and the width of the picture, which are unfortunately -858993460 in debug mode, so the whole size of my picture overflows everytime, so I get a bad allocation error. I use VS 2013, could anyone help me out with this one ?

unsigned char* readBMP(char* filename)
{

int i;
char info[54];
std::ifstream ifs(filename, std::ifstream::binary);
ifs.read(info, 54);

// extract image height and width from header
int width = *(int*)&info[18];
int height = *(int*)&info[22];

int size = 3 * width * height;

char* data = new char[size]; // allocate 3 bytes per pixel

ifs.read(data, size);
ifs.close();
return (unsigned char*)data;

}

推荐答案

我猜您无法打开文件,因此您的读取必须失败.

I guess you failed to open the file, so your read must been failed.

您可以检查: if(ifs.is_open()){/*好*/}

您还可以检查: if(ifs.read(...)){/* good */}

尝试此代码:

unsigned char* readBMP(char* filename)
{

int i;
char info[54];
std::ifstream ifs(filename, std::ifstream::binary);
if(!ifs.is_open()){ 
   std::cerr<<" failed to open file"<<std::endl;
   return NULL;
 }
if(!ifs.read(info, 54)) {
  std::cerr<<" failed to read from file"<<std::endl;
  return NULL;
} 

// extract image height and width from header
int width = *(int*)&info[18];
int height = *(int*)&info[22];

int size = 3 * width * height;

char* data = new char[size]; // allocate 3 bytes per pixel

ifs.read(data, size);
ifs.close();
return (unsigned char*)data;

}

这篇关于Ifstream读取错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆