Search code examples
c++filefile-iofstream

C++ file handling (structures)


Following code, when compiled and run with g++, prints '1' twice, whereas I expect '1' to be printed only once, since I am dumping a single structure to the file, but while reading back it seems to be reading two structures. Why?

#include <iostream.h>
#include <fstream.h>

int main(){
    struct student
    {
        int rollNo;
    };
    struct student stud1;
    stud1.rollNo = 1;

    ofstream fout;
    fout.open("stu1.dat");
    fout.write((char*)&stud1,sizeof(stud1));
    fout.close();

    ifstream filin("stu1.dat");
    struct student tmpStu;
    while(!filin.eof())
    {
          filin.read((char*)&tmpStu,sizeof(tmpStu));
      cout << tmpStu.rollNo << endl; 
    }
    filin.close();
}

Solution

  • eof only gets set after a read fails, so the read runs twice, and the second time, it doesn't modify the buffer.

    Try this:

    while(filin.read((char*)&tmpStu,sizeof(tmpStu)))
    {
        cout << tmpStu.rollNo << endl; 
    }
    

    Or

    while(!filin.read((char*)&tmpStu,sizeof(tmpStu)).eof())
    {
        cout << tmpStu.rollNo << endl; 
    }
    

    Read returns a reference to filin when called, which will evaluate to true if the stream is still good. When read fails to read any more data, the reference will evaluate to false, which will prevent it from entering the loop.