LenItsuki LenItsuki -4 years ago 164
C++ Question

read binary data by C++

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

file.read( ( char * ) &d, sizeof( unsigned char ) );

cout << d << endl;


return 0;

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download