将图像读取为二进制文件

时间:2013-12-05 18:40:02

标签: c++ image file binaryfiles

我正在阅读关于codeproject的this项目。它将图像作为二进制对象读取,然后检查其标头的前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;
}

输出结果为:

Reading 11 characters...
b
b
b
b
b
b
b
b
b
b
b
error: only 0 could be readdata is

所以,我知道第一行

  

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

输入if子句后

成功。但之后没有收到任何输入。我知道因为它是二进制输入,格式化输入如是&gt;&gt;不应该使用c 。但是只有当 is.read()不成功时才写这个。

有谁能告诉我这是什么问题?

1 个答案:

答案 0 :(得分:2)

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

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