1

I try to read binary data by C++ program below. But it can not display values. The data is saved as 8bit unsigned char. Let me know how to solve it.

#include <iostream>
#include <fstream>
using namespace std;

int main(int argc,char *argv[])
{
    if(argc!=2)
    {
        cout << "argument error" << endl;
        return 1;
    }

    ifstream file (argv[1], ios::in|ios::binary);
    //ifstream fin( outfile, ios::in | ios::binary );

    if (!file)
    {
        cout << "Can not open file";
        return 1;
    }

    unsigned char d;

    while(!file.eof())
    {
        file.read( ( char * ) &d, sizeof( unsigned char ) );

        cout << d << endl; 
    }

    file.close(); 

    return 0;
}
LenItsuki
  • 57
  • 8

1 Answers1

6

First of all don't do while (!file.eof()).

Then for your problem: It is that you output a character. That means the stream will attempt to print it as a character, which will not be correct for binary data.

If you want to print the values you read, you need to convert it to integers. Something like

std::cout << std::hex << std::setw(2) << std::setfill('0') <<
          << static_cast<unsigned int>(d);

The above should print out the values as 2-digit hexadecimal numbers. The important bit is the static_cast.

Community
  • 1
  • 1
Some programmer dude
  • 363,249
  • 31
  • 351
  • 550
  • The value can show 0 and 1 by the fixed program as you said. I would like to show 0 and 255 in 8 bit. Let me know how to do it. – LenItsuki Aug 25 '16 at 10:12
  • @LenItsuki I'm not sure what you mean... Do you mean that each *byte* in the input file can only be a single `1` or `0`? Can you please edit your question to include a partial hex-dump of the input file (no, no one is going to download and open an unknown file like the one you link to). – Some programmer dude Aug 25 '16 at 10:47
  • I mistake the values contained in the file. 0 and 1 are OK! Thank you for your advice. – LenItsuki Aug 25 '16 at 12:23