Hi,
I have grasped all the basic stuff in C++. Variables, functions, classes, struvts, etc. Now I am trying to learn how to read binary files in c++ but I just can't seem to get it right.
I know how to open the file in binary mode, that's not the problem. The problem is how I should print the data to screen. If I read with fread and put them in an int I have more or less screwed up everything, right? Is there a way to output a single byte so I can see if my fread is accurate?
i.e
fread(buffer, 10, 1, file) // This reads 10 bytes into the buffer from file
but I have no other option than to use int as a buffer, so if I print what's in buffer[1] I get a huge INT, is that my binary number (which needs translation) or am I doing something fundamentally wrong?
Sorry if I seem confused, this is my first steps outside the first level of c++ programming ..
Reading Binary Files in c++
Re:Reading Binary Files in c++
This depends on what kind of data are in your file.
If you literally want to read some bytes and display them, you can read into an array of chars. This code will read 10 bytes and display them as hex:
If you literally want to read some bytes and display them, you can read into an array of chars. This code will read 10 bytes and display them as hex:
Code: Select all
char buffer[10];
unsigned i;
fread(buffer, 10, 1, file);
for (i = 0; i < 10; i++)
printf("%02x ", buffer[i]);
printf("\n");