Reading and writing structures

I am writing a code that will accept a structure information from user, and write the structure in a file. After a structure is written, I read the structure from the file, and write it. But it isn't working as I was expecting. It seems as if it is writing data to file, but not reading it.

Btw, I am using Turbo C++.

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
 #include<fstream.h>
#include<conio.h>

struct person{
	char name[25];
	float balance;
	}p1;

void main()
{
	clrscr();
	ofstream write("file.dat",ios::out|ios::binary);
	cout<<"\nEnter name: ";
	cin.getline(p1.name, 25);
	cout<<p1.name;
	cout<<"\nEnter balance: ";
	cin>>p1.balance;
	cout<<p1.balance;
	write.write((char*)&p1, sizeof(person));
	ifstream read("file.dat",ios::in|ios::binary);
	cout<<"\nRecord copied\n";
	p1.balance=0;
	for(int i=0;p1.name[i]!='\0';i++)p1.name[i]='.';
	read.read((char*)&p1,sizeof(person));
	cout<<p1.name<<p1.balance;
	read.close();
	write.close();
	getch();
	}


Please help me out!
After writing to the file you need to close it before you can read from it.
Topic archived. No new replies allowed.