Please help me with this fstream code. It has some silly error somewhere.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<fstream>
#include<iostream>
using namespace std;
class student
{
	char name[30];
	int roll;
	public:
	void getdata(int i)
	{
		cout<<"\n\a Enter name of student " <<i<<" : ";
		cin>>name;
		cout<< "\n\a Enter roll no : ";
		cin>>roll;
	}	
	void putdata(int i)
	{
		cout<<"\n\a Name of student " <<i<<" : "<<name;
		
		cout<< "\n\a Roll no : "<<roll;
		
	}	

};

int main()
{
	student s;
	int i=1;char op;
	ofstream fo("first file.DAT",ios::binary|ios::ate);
	while(fo)
	{
     	s.getdata(i);
		i++;
		fo.write((char*)&s,sizeof(s));
		cout<< "\n\a More students ?? (Y/N)";
		cin>>op;
		if(op=='y'||op=='Y')
		continue;
		else
		fo.close();
    }
    i=1;
	ifstream fi("first file.DAT",ios::binary|ios::ate);
	while(!fi.eof())
	{
  		fi.read((char*)&s,sizeof(s));
  		s.putdata(i);
  		i++;
	}
	fi.close();
}

This is supposed to take input of n student's Name and roll no and then read it from file.
but here is output
https://fbcdn-sphotos-h-a.akamaihd.net/hphotos-ak-xpa1/v/t34.0-12/10877885_844071928977885_1097137846_n.jpg?oh=a67ba247d82d0c0825aff4f038d4a065&oe=5498FA49&__gda__=1419295849_d4c1b77ad340a8cd1352d26caa35fa7e
https://en.wikipedia.org/wiki/Redirection_(computing)

1
2
3
4
while(fo)
		else
			fo.close(); //this does not set any fail flags
    }
your loop goes one time too many. The last time nothing is wrote to the file (it is closed) but the 's' object does change.

Then you try to read, you are standing 'at the end' of the file, there is nothing there.
But it is not eof(), so the loop executes, however line 47 fails, it has no effect on 's', that maintains the last value.


I'm not sure of what is the rule for an invalid reading operation, I wouldn't expect the object to remain the same.
Not sure what error you are getting but as ne555 pointed towards; just because you closed fo doesn't make fo null.
ofstream will return null if it fails to init.
Last edited on
Thanks a ton.
Anything wrong with this line if I have included <fstream>
1
2
	ifstream fi("first file.DAT",ios::binary);
	fi.seekg(0);

the compiler is saying that seekg was not declared in this scope
Topic archived. No new replies allowed.