Home > Enterprise >  Problem with reading a binary file in cpp?
Problem with reading a binary file in cpp?

Time:12-02

I have a binary file called "input.bin" where every character is of 4 bits. The file contains this kind of data:

0f00 0004 0018 0000 a040 420f 0016 030b
0000 8000 0000 0000 0000 0004 0018 0000

where 0f is the first byte.

I want to read this data and to do that, I am using the following code:

#include <string>
#include <iostream>
#include <fstream>

int main()
{
      char buffer[100];
      std::ifstream myFile ("input.bin", std::ios::in | std::ios::binary);
      myFile.read (buffer, 100);

      if (!myFile.read (buffer, 100)) {
        std::cout << "Could not open the required file\n";
      }
      else
      {
        for (int i = 0; i < 4; i  )
        {
          std::cout << "buffer[" << i << "] = " << static_cast<unsigned>(buffer[i]) << std::endl;
        }
        myFile.close();
      }
    return 0;
}

Currently I am printing just four bytes of data, and when I run it, I get this output:

buffer[0] = 0
buffer[1] = 24
buffer[2] = 0
buffer[3] = 0

Why is it not printing the value of 0f and just printing the value of 18 in index 1 whereas it is actually at index 6?

CodePudding user response:

The problem is here

myFile.read (buffer, 100);

if (!myFile.read (buffer, 100)) {

where you read twice, and thus ignore the first 100 bytes (if there are more than 100 of them).

Remove the first read, or change the condition to if (!myFile)

CodePudding user response:

You print the contents of the data as characters. And none of the first four bytes are really printable characters.

You need to print them as (unsigned) integers:

// Unsigned bytes to avoid possible sign extensions in conversions
unsigned char buffer[100];

...

// Convert the bytes to unsigned int for printing their numerical values
std::cout << "buffer[" << i << "] = " << static_cast<unsigned>(buffer[i]) << '\n';
  • Related