-1

I'm trying to read a .bmp file. I succesfully read the initial B and M characters, but after that i get only 0, if wrote into an integer or blanks, if wrote into a char. According to https://en.wikipedia.org/wiki/BMP_file_format there should be the size of the file, some reserved Bytes and the Offset of my file.

int main(){
    std::ifstream file("bmp.bmp");
    char token;
    int num;
    file >> token;
    if(token != 'B')
        std::cerr << "file is not a .bmp";
    file >> token;
    if(token != 'M')
        std::cerr << "file is not a .bmp";
    for(int i = 0; i < 3; i++){
        file >> num;
        std::cout << num << "\n;
    }
    file.close
}        

All this Code will print on the consol is:
0
0
0
Why am i not getting the expected Output?

1 Answers1

1

You need to do binary reads (not text like you are doing now)

std::ifstream file("bmp.bmp", std::ios_base::binary);

file.read((char*)&num, sizeof num);

where num is declared at the correct size (int32_t or int16_t).

In addition you may need to correct the numbers for endianess.

I recommend doing some reading on binary I/O in C++ before going any further.

john
  • 85,011
  • 4
  • 57
  • 81
  • Thanks! Do you have any recommendations, where to do so? – a_familiar_wolf Jan 30 '18 at 15:04
  • MS once decided to remark end of lines in text files by two characters: CR and LF (carriage return and line feed, ASCII codes 13 and 10). In C and C++, in opposition, end of line is denoted by LF only. (C was originally developed for Unix.) Therefore, MS had a problem which was solved "under the hood" of file I/O by converting CR/LF to LF in reading and LF to CR/LF in writing. This works well for text files but may accidentally destroy contents of binary files. Hence, binary file I/O can be remarked as such. Btw. the binary mode does nothing on systems where the CR/LF issue does not exist. – Scheff's Cat Jan 30 '18 at 16:04
  • @Scheff the even bigger problem is Ctrl-Z, ASCII code 26. It indicates end-of-file and causes all reading to cease beyond that point. – Mark Ransom Jan 30 '18 at 22:58
  • @MarkRansom Wow. I even didn't notice this issue until today. (Have to try out once.) Concerning CR/LF and BMP, I once wrote an answer to a very similar issue: [SO: Copying a bmp in c](https://stackoverflow.com/a/46477480/7478597). – Scheff's Cat Jan 31 '18 at 07:26