Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read 32-bit integer from binary file in C++?

Tags:

c++

file

fstream

My binary file looks like this.

00000000: 0000 0803 0000 ea60 0000 001c 0000 001c
00000010: 0000 0000 0000 0000 0000 0000 0000 0000

left column is address.

I just tried to read 0000 0803(=2051) as follows

ifstream if;
if.open("file");
uint32_t a;
if >> a;

As expected...It did not work :-(
a was just 0 after execution.
I tried long, int, unsigned int, unsigned long. All failed.

Why these are not working and how can I achieve the goal?

like image 564
plhn Avatar asked Aug 18 '15 07:08

plhn


2 Answers

You have two issues:

  1. Insuring you read the bytes you intend (no fewer, no more) from the stream.

    I'd recommend this syntax:

    uint32_t a;

    inFILE.read(reinterpret_cast<char *>(&a), sizeof(a));

  2. Insure you're interpreting those bytes with the correct byte order.

    Q: If you're on a PC, your CPU is probably little endian. Do you know if your data stream is also little-endian, or is it big endian?

    If the data is big-endian, I'd consider the standard networking functions to accomodate byte order: ntohl(), etc: http://www.retran.com/beej/htonsman.html

ALSO:

Follow Hcorg's and Daniel Jour's advice: don't forget about the "open mode" parameter, and don't forget to check for "file open" errors.

like image 78
paulsm4 Avatar answered Nov 08 '22 21:11

paulsm4


Open file in binary mode and then use read() method, something like:

uint32_t a;
ifstream file ("file", ios::in | ios::binary);
if (file.is_open())
{
     file.read ((char*)&a, sizeof(a));
}
like image 5
VolAnd Avatar answered Nov 08 '22 22:11

VolAnd