读取图像为二进制文件

问题描述 投票:1回答:1

我读到 这个 项目上的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;
}

输出结果是:

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

所以,我知道第一行

std::ifstream is ("warren.jpg", std::ifstream::binary)。

是成功的,因为输入了if子句。但之后就没有收到任何输入。我知道,因为这是一个二进制输入,格式化的输入如 是>>c 不应使用。但我写这个只是在 is.read() 是不成功的。

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

c++ image file binaryfiles
1个回答
3
投票

你将不得不打开你的文件,并同时使用 ios::binary | ios::in 旗帜。

std::ifstream ifs (L"c:\\james.rar", std::ios::binary | std::ios::in);
© www.soinside.com 2019 - 2024. All rights reserved.