Friday, June 25, 2010

C++ File handling fstream problem

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(); }
 
 Ans : 
 When you use read() to input from a file stream, eof becomes true only with the first attempt to read beyond the end-of-file, not upon exactly reaching it!
The attached code uses peek() and works for me.
 
 
 #include <iostream> #include <fstream> using namespace std;   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.peek() != EOF)         {           filin.read((char*)&tmpStu,sizeof(tmpStu));           cout << tmpStu.rollNo << endl;         }         filin.close(); }
 
 Ans 2 : 
 Solution for the same problem on stackoverflow :
while(filin.read((char*)&tmpStu,sizeof(tmpStu)))
{
   cout << tmpStu.rollNo << endl; 
}
Or
while(!filin.read((char*)&tmpStu,sizeof(tmpStu)).eof())
{
   cout << tmpStu.rollNo << endl; 
}
from :http://stackoverflow.com/questions/440167/doubt-in-c-file-handling

No comments:

Blog Archive