문제

I was reading about this project on codeproject. It reads images as a binary object and then checks the first 10 bytes of its header. I wrote the following code to run on Windows machine:

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);

was successful as the if clause was entered. 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. But I wrote this only when is.read() was unsuccessful.

Can anyone please tell me what the problem is?

도움이 되었습니까?

해결책

You will have to open your file with the both the ios::binary | ios::in flags:

std::ifstream ifs (L"c:\\james.rar", std::ios::binary | std::ios::in);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top