Search code examples
c++ifstream

Reading a binary file and interpret as integers


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;
}

Solution

  • 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.