首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ifstream读取错误

Ifstream读取错误
EN

Stack Overflow用户
提问于 2015-05-19 05:55:45
回答 1查看 6.6K关注 0票数 3

我一直在尝试用ifstream读取一个bmp文件,但是它在没有调试的情况下工作得很好,当我在调试模式下运行它时,它失败了。一开始,我读取了54字节的信息,以获得图片的高度和宽度,不幸的是,在调试模式下,它们是-858993460,所以每次图片的整个大小都会溢出,所以我得到了一个糟糕的分配错误。我使用的是VS 2013,有人能帮我解决这个问题吗?

代码语言:javascript
复制
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;

}
EN

回答 1

Stack Overflow用户

发布于 2015-05-19 06:20:58

我猜你打开文件失败了,所以你的读取一定失败了。

你可以查看:if (ifs.is_open()) { /* good*/}

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

尝试以下代码:

代码语言:javascript
复制
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;

}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30313409

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档