C++ 将图像作为二进制文件读取

C++ 将图像作为二进制文件读取,c++,image,file,binaryfiles,C++,Image,File,Binaryfiles,我在读一本关于codeproject的书。它将图像作为二进制对象读取,然后检查其头的前10个字节。我编写了以下代码以在Windows计算机上运行: int main () { std::ifstream is ("warren.jpg", std::ifstream::binary); if (is) { // get length of file: // is.seekg (0, is.end); int length = 11; is.seekg (0

我在读一本关于codeproject的书。它将图像作为二进制对象读取,然后检查其头的前10个字节。我编写了以下代码以在Windows计算机上运行:

int main () {

  std::ifstream is ("warren.jpg", std::ifstream::binary);
  if (is) {
    // get length of file:
   // is.seekg (0, is.end);
    int length = 11;
    is.seekg (0, is.beg);

    char * buffer = new char [length];


    std::cout << "Reading " << length << " characters... "<<endl;
    char c='b';
    for(int i=0;i<11;i++)
    {
        is>>c;
    cout<<c<<endl;  //this just prints b 10 times
    }

    // read data as a block:
    is.read (buffer,length-1);
    buffer[length-1]= '\0';

    if (is)
      std::cout << "all characters read successfully.";
    else
      std::cout << "error: only " << is.gcount() << " could be read";
    is.close();

    cout<<"data is "<<buffer<<endl;

    // ...buffer contains the entire file...

    delete[] buffer;
  }

  return 0;
}
所以,我知道第一行

std::ifstream是(“warren.jpg”,std::ifstream::binary)

已成功输入if子句。但是在那之后,没有任何东西被接收作为输入。我知道,由于它是二进制输入,因此不应使用格式化输入,如is>>c。但是我只有在is.read()不成功时才写这篇文章


有谁能告诉我问题出在哪里吗?

您必须使用
ios::binary | ios::in
标志打开文件:

std::ifstream ifs (L"c:\\james.rar", std::ios::binary | std::ios::in);

倒转方向,找出
is.read()
失败的原因。您不需要同时使用
ios::binary | ios::in
flags@KristerAndersson...that我犯了个愚蠢的错误。。。thanks@avinash这解决了你的问题吗???@user1944429.是的,这确实允许我阅读,但当我试图打印它时,输出是垃圾(可能是因为读入值是二进制的,无法正确打印)。但随后,我使用了codeproject代码中使用的memcmp()函数(其中的链接有问题),可以正确定义图像类型
std::ifstream ifs (L"c:\\james.rar", std::ios::binary | std::ios::in);