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;
}
0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 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).
I mistake the values contained in the file. 0 and 1 are OK! Thank you for your advice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.