Search code examples
c++filefile-ioistream

ifstream does not read `0a` byte existing in the file


I want to read the first 7 bytes of my file. this is the data of my file:

42 4d b6 fc 0a 00 00

I use this code to do that:

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;


int main()
{
    ifstream r("TestFile.abc", ios::binary);
    unsigned char info[7];
    for(int i = 0 ; i < 7; i++){
        r >> info[i];
    }

    for(int i = 0 ; i < 7; i++){
      std::stringstream ss;
      ss << std::hex << (int) info[i]; // int decimal_value
      std::string res ( ss.str() );
      cout << i << setw(10) << info[i] << setw(10) << res << endl;
    }



   return 0;;
}

and this the output:

0         B        42
1         M        4d
2         ╢        b6
3         ⁿ        fc
4                   0
5                   0
6                   0

Process returned 0 (0x0)   execution time : 0.032 s
Press any key to continue.

Why 0a byte has replaced with 0?


Solution

  • >> skips whitespace, 0a is a whitespace character. Try this

    info[i] = r.get();
    

    get reads a single byte without skipping anything (excepting possible end of line conversions, but you've already acccounted for that by using ios::binary)