Search code examples
c++file-iobinaryfilesifstream

Reading and writing integers from/to a binary file in C++


The trying to write a simple program that would write integers value into a file, then read and display the integers in the order it was written. The integers written into the file are {0,2,....18}. The following is the code:

// Example program
#include <iostream>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
using namespace std;

int main()
{
    typedef unsigned int uint32_t;
    // Write to file
    std::ofstream osObj;
    string filename = "testFile";
    osObj.open(filename.c_str(), std::ofstream::binary);

    for (uint32_t i=0; i<10; ++i)
    {
        uint32_t a = i*2;
        osObj.write(reinterpret_cast<const char *>(&a), sizeof(a));
        //osObj.write((char *)(&a), sizeof(a));
    }

    //read from file
    std::ifstream isObj;
    isObj.open(filename.c_str(), std::ofstream::binary);
    if (isObj.fail()) { cout<<"Failed to open file"<<endl; }

    for (uint32_t i=0; i<10; ++i)
    {
        char val[sizeof(uint32_t)];
        isObj.read(val, sizeof(val));
        uint32_t* valUint = reinterpret_cast<uint32_t *>(val);
        cout<<*(valUint)<<endl;
    }
    return 0;
}

This doesn't produce the expected result. I'm getting the following output:

62586880
62586880
62586880
62586880
62586880
62586880
62586880
62586880
62586880
62586880

The byte ordering is little-endian. What am I missing?


Solution

  • You shouldn't add i to valUint. You're only reading one integer into val, so the integer you just read is at the address pointed to by valUint. It's not an array of integers, so there's no reason to index the pointer.

        cout<< *valUint << endl;
    

    A simpler way to write it is:

    for (unint32_t i = 0; i < 10; ++i) {
        uint32_t val;
        isObj.read(reinterpret_cast<char *>&val, sizeof val);
        cout << val << endl;
    }
    

    Also, you should do osObj.close() at the end of the writing loop. The file is buffered, and the buffer may not have been flushed. If you checked for errors when reading, you probably would have noticed that nothing was being read from the file.