我一直在尝试用 ifstream 读取一个 bmp 文件,但是它在没有调试的情况下工作正常,当我在 Debug模式下运行它时它失败了。一开始我读了54个字节的信息,来获取图片的高度和宽度,不幸的是在 Debug模式下是-858993460,所以我的图片每次都溢出,所以我得到了一个不好的分配错误。我使用 VS 2013,谁能帮我解决这个问题?
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;
}
最佳答案
我猜你打开文件失败了,所以你的读取一定是失败了。
你可以检查:if (ifs.is_open()) {/* good*/>
您还可以检查: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;
}
关于c++ - ifstream读取错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30313409/