Search code examples
c++c++11fstreambinaryfilesstdvector

Using fstream to read from a binary file and store the results in a vector


I'm working on a project for my CS202 class. I have a supplied binary file of unknown size called data.dat and need to read integers (which I don't know in advance) from the file and store them in a properly sized vector. I have to use fstream() for the filestream and I have to use the reinterpret_cast<char *>() for the conversion. My code looks like this:

fstream filestream2;
//reading binary data from supplied data.dat file
filestream2.open("data.dat", ios::in | ios::binary);
vector<int> v;
filestream2.seekg(0, filestream2.end);
long length = filestream2.tellg();
v.resize(length);
filestream2.read(reinterpret_cast<char *>(&v[0]), length);
for(int num = 0; num < length; num++)
{
    cout << v[num] << " ";
}

In theory, the vector should hold all of the integers from the file and print them to stdout, but my output is simply about 50,000, 0s followed by program exited with exit code 0 I'm relatively new to C++ syntax and libraries and I just cannot figure out what I'm doing wrong for the life of me. Thanks in advance.


Solution

  • When you use

    filestream2.seekg(0, filestream2.end);
    long length = filestream2.tellg();
    

    you get the number of characters in the file, not the number of items in the vector. Consequently, you will need to use length/sizeof(int) when you want use the size of the vector.

    v.resize(length);
    

    is incorrect. It needs to be

    v.resize(length/sizeof(int));
    

    and

    for(int num = 0; num < length; num++)
    {
        cout << v[num] << " ";
    }
    

    is incorrect. It needs to be

    for(int num = 0; num < length/sizeof(int); num++)
    {
        cout << v[num] << " ";
    }