Writing to a binary file and displaying its contents

This is my program. It takes the necessary inputs but doesn't give the required output:
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
   //Binary files
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<iomanip.h>
#include<stdio.h>

class student
{
	int roll_no,mark[6];
	char name[50];
	public:
	void input();
	void show();
};

void student::input()
{
	int mark[6];
	cout<<endl<<"Enter name"<<endl;
	gets(name);
	cout<<"Enter roll no."<<endl;
	cin>>roll_no;
	cout<<"Enter marks of the 6 subjects"<<endl;
	for(int i=0;i<6;i++)
	{
		cin>>mark[i];
	}
}

void student::show()
{
	float p=0;
	int i;
	cout<<setw(10)<<roll_no<<setw(10)<<name;
	for(i=0;i<6;i++)
	{
		cout<<mark[i]<<"   ";
		p+=mark[i];
	}
	p=p/6;
	cout<<setw(10)<<p;
}

void main()
{
	clrscr();
	int n;
	student s;
	fstream f;
	f.open("Student.dat", ios::binary|ios::out|ios::app);
	cout<<"Enter the total number of students"<<endl;
	cin>>n;
	for(int i=0;i<n;i++)
	{
		s.input();
		f.write((char *)&s,sizeof(s));
	}
	f.close();
	cout<<endl<<setw(10)<<"Roll no"<<setw(10)<<"Name"<<setw(20)<<"Marks"<<setw(10)<<"                     Percentage"<<endl;
	f.open("Student.dat", ios::binary|ios::in);
	while(!f.eof())
	{
		f.read ((char*)&s,sizeof(s));
		if(f.eof())
		{
		break;
		}
		else
		{
		s.show();
	}        }
	getch();
	}
Last edited on
Never use gets(), this dangerous C function can never be used safely. Since your using C++ prefer using C++ streams instead.

Since you're using such an old pre-standard compiler I don't recommend re-using streams unless you make sure you clear the error flags between re-use. Before the C++11 standard just closing and opening streams didn't clear() the stream error flags.

You really really should consider getting a newer standard compliant compiler and abandon your current compiler.

Topic archived. No new replies allowed.