user3764893
user3764893

Reputation: 707

How to read exactly one byte in a binary file in C++

I am trying to a read a single byte from a binary file, and I am getting inaccurate results.

This is the content of binary file:

00000000 00 04 0A 07 00 00 00 00 00 00 74 00 00 00 00 61 69 6E 62 6F 77 00 ..........t....ainbow.

The point is that I can read more than one byte, but I just can't read exactly one byte. If tried to read the third byte 0A which is equal to 10, instead it gives me a value of 32522 or in hexadecimal 7F0A. What am I missing here?

#include <iostream>
#include <fstream>
#include <cstring>
#include <fstream>

using namespace std;

int main()
{
    fstream file("foo.daf", ios::in | ios::out | ios::binary);

    file.seekg(2);

    int x;

    file.read(reinterpret_cast<char *>(&x), 1);

    cout<<x<<endl;

    return 0;
}

Upvotes: 1

Views: 26326

Answers (3)

Ed Heal
Ed Heal

Reputation: 60037

The following code is what you are looking for:

unsigned char x;
file.read(&x, 1);
cout << static_cast<int>(x) << endl;

It reads in a character and then converts it to an integer.

Upvotes: 7

WonderMonster
WonderMonster

Reputation: 220

The problem is that you are reading an int. An Int is more than one byte on almost all systems. Int's are commonly 4 bytes, and sometimes 8 bytes. You really want to read in a char as the previous comment says.

int main()
{

    fstream file("foo.daf", ios::in | ios::out | ios::binary);

    file.seekg(2);

    char x;

    file.read((&x), 1);

    cout<<x<<endl;

    return 0;
}

Upvotes: 2

Jarod42
Jarod42

Reputation: 218238

x is not initialized, and you modify only one byte of it, so you have garbage for the other bytes.

Use directly the correct type should solve your issue (and avoid a cast).

char x;

Upvotes: 8

Related Questions