0

I have a binary file that contains floats so that every 4 bytes are a float. I'm not sure how I can read in a way that every four bytes would be stored as a float so I can do whatever I need with it.

Here's my code:

int main()
{
    float i;
    std::ifstream inFile("bin_file", std::ios::binary);
    while (inFile >> i)
    {
        std::cout << i;
    }
    inFile.close();
    return 0;
}

In that case, it won't even enter the while loop unless I define i as a char. I guess that's because it reads 1 byte every time and can't store it as a float. Btw I've checked and the file opens.

Thanks!

user3265447
  • 123
  • 2
  • 9
  • 1
    The first thing you need to do is determine endian-ness. https://stackoverflow.com/questions/701624/difference-between-big-endian-and-little-endian-byte-order. `std:bit_cast` is c++20 is a good way to convert to floats. – doug Jun 05 '21 at 23:23
  • 1
    See answer to [Reading binary file to unsigned char array and write it to another \[duplicate\]](https://stackoverflow.com/q/22129349/3422102) the question it is a duplicate of does not address the issue (how to handle binary input with `read()`). – David C. Rankin Jun 05 '21 at 23:33

1 Answers1

5

The operator>> in streams is designed for formatted data (i.e. strings). You want to use read instead:

int main()
{
    float i;
    std::ifstream inFile("bin_file", std::ios::binary);
    while(inFile.read(reinterpret_cast<char*>(&i), sizeof(i))) {
        std::cout << i;
    }
    inFile.close();
    return 0;
}
Casey
  • 10,297
  • 11
  • 59
  • 88