简体   繁体   English

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

[英]reading an image as a binary file

I was reading about this project on codeproject.我在 codeproject 上阅读了这个项目。 It reads images as a binary object and then checks the first 10 bytes of its header.它将图像作为二进制对象读取,然后检查其标头的前 10 个字节。 I wrote the following code to run on Windows machine:我编写了以下代码以在 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;
}

The output was:输出是:

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

So, I know that the first line所以,我知道第一行

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

was successful as the if clause was entered.成功,因为输入了 if 子句。 But after that nothing is received as input.但在那之后,没有收到任何输入。 I know that as it is a binary input, formatted input like is >> c should not be used.我知道因为它是一个二进制输入,所以不应该使用像is >> c这样的格式化输入。 But I wrote this only when is.read() was unsuccessful.但是我只在is.read()不成功时才写了这个。

Can anyone please tell me what the problem is?谁能告诉我是什么问题?

You will have to open your file with the both the ios::binary | ios::in您必须同时使用ios::binary | ios::in打开您的文件ios::binary | ios::in ios::binary | ios::in flags: ios::binary | ios::in标志:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM