-1

I'm trying to interpret a binary file as a series of integers and read the values to a vector. However, the line ifs >> n; always returns 0 and eof is always false, the file position is not updated. If I change the type to char it works but that is not what want to achieve. How can I make the code work as I want?

int readAsNumber(const char* fileName, vector <int> &content)
{
    ifstream ifs;
    int n;

    ifs.open(fileName, ifstream::in | ifstream::binary);
    while (ifs.eof() == false)   // Never terminates 
    {
        ifs >> n;               // Always sets n = 0
        content.push_back(n);   // Saves 0
    }
    ifs.close();
    return 0;
}
  • All files are binary. Also, that `binary` flag when opening doesn't do what you think it does. Streams still do formatted, textual IO. – Ulrich Eckhardt Jan 13 '20 at 14:29
  • Read about why you should not use `eof()` [here](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – molbdnilo Jan 13 '20 at 14:30
  • while (ifs >> n) content.push_back(n); immediately terminates the loop –  Jan 13 '20 at 14:32

1 Answers1

1

The input operator >> reads and interprets the input as text.

If the file contains raw binary data you need to read as raw data as well:

int value;
while (ifs.read(reinterpret_cast<char*>(&value), sizeof value))
    content.push_back(value);

Remember that storing raw binary data like this is not portable, and is really not recommended.

Some programmer dude
  • 363,249
  • 31
  • 351
  • 550