Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 279
simplfuzz Avatar asked Dec 05 '25 06:12

simplfuzz


1 Answers

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.

like image 153
Eclipse Avatar answered Dec 07 '25 19:12

Eclipse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!