ardiyu07
ardiyu07

Reputation: 1800

How to read hex values from a file using fstream in c++?

As the title says, how do you read hex values using fstream?

i have this code: (let's say we have "FF" in the file.)

fstream infile;
infile.open(filename, fstream::in|fstream::out|fstream::app);

int a;
infile >> std::hex;
infile >> a;
cout << hex << a;

but this does not give me any output instead of ff. I know there is a fscanf(fp, "%x", val) but I am curious is there any way to do this using stream library.

UPDATE:

My code was right all along, it turns out my error was I couldn't read "FFF" and put it in variable a,b,c like this

while (infile >> hex >> a >> b >> c)
  {
    cout << hex << a << b << c << "\n";
  }

Can somebody help me with this? do I have to separate every HEX values i want to read with space? because infile >> hex >> setw(1) doesn't work..

Upvotes: 11

Views: 53787

Answers (4)

Than21
Than21

Reputation: 321

Also make sure that your input file is written using a Hex editor and not a regular text editor. Otherwise a file foo.txt containing a character 'a' will be read as 0x61 and printed as 0x61 instead of 0xa. A nice Hex editor for linux is "Bless".

Upvotes: -2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272487

This works:

int main()
{
    const char *filename = "blah.txt";
    ifstream infile(filename, fstream::in);

    unsigned int a;
    infile >> hex >> a;
    cout << hex << a;
}

Upvotes: 7

Bernd Elkemann
Bernd Elkemann

Reputation: 23550

You can use the hex modifier

int n;
cin >> hex >> n;

Upvotes: 12

Nekresh
Nekresh

Reputation: 2988

You have to chain std::hex when reading, the same way you chain it for writing :

infile >> std::hex >> a;

Upvotes: 6

Related Questions