c++ - ifstream读取错误

标签 c++ debugging visual-c++ fstream ifstream

我一直在尝试用 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/

相关文章:

c++ - 写 MethodChannel 桥和 Dart :ffi bridge to run c/c++ code to get the response? 有什么区别

c++ - 堆栈溢出多层感知器

c++ - cvtColor 断言失败(带有 C++ 的 OpenCV)

java - 无法实例化 java 类

c++ - Visual Studio 调试持续未处理的异常

c++ - 如何解决 MSCV 中 Boost 文件系统库的 LNK1104 错误?

c++ - 重载给我错误 : no match for ‘operator<’

java - Hibernate criteria.list() 在神秘情况下抛出 NullPointerException

c++ - 为什么/如何将非宽字符串传递给 wstringstream::operator<<?

visual-c++ - RC2176 : old DIB in res\MyApp. ico;在VC++ 2008中通过SDKPAINT传递它