File Handling problem

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

class employee
{
int code;
char name[30];
float salary;
public:
	void input()
	{
	cin>>code>>name>>salary;
	}
	void show()
	{
	cout<<code<<name<<salary<<endl;
	}
};

void writetofile()
{
employee e;
e.input();
ofstream f;
f.open("first.dat",ios::binary|ios::app);
f.write((char*)&e,sizeof(e));
f.close();
}

void readfromfile()
{
employee e;
ifstream f;
f.open("first.dat",ios::binary|ios::app);
f.read((char*)&e,sizeof(e));
e.show();
f.close();
}

void main()
{
clrscr();
writetofile();
readfromfile();
getch();
}


As I am doing file handling for the first time, i dont know whats wrong with the program but it gives the wrong output. Please help me.
  27 f.open("first.dat",ios::binary|ios::trunc);

  32 f.open("first.dat",ios::binary);

Hope this helps.


[edit]
BTW, this is not the best way to do it. Google around "serialization" for more. I know that it is a lot of work, but it is safer to do it right.

For a simple solution, check out Boost.Serialization
http://www.boost.org/doc/libs/release/libs/serialization/doc/index.html

I don't know if it will work with your ancient compiler, though.
Last edited on
thanks for the help, but this still gives me the same answer.

C:\m\Programming\x> a
177 Johnny 12.50
177Johnny12.5

C:\m\Programming\x>

It works fine for me. Are you trying to input a name with spaces in it (like, first and last name)?
Topic archived. No new replies allowed.