Data File Handling Code Does not work

I have recently installed code::blocks and was writing a basic progra of data file handling... The program is not working and stops responding in between when I try to read the contents of the file...

I downloaded a sample code but it works fine.. although the codes are almost the same.. I tried usinf ios::ate instead of ios::app...

When I enter 1 contact it displays o/p correctly
When 2 contacts the second contact twice
When 3 contacts the output is some garbage symbols...

Many times it just stops responding..

Please can you tell me where am I making a mistake..

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
#include<iostream>
#include<cstdlib>
#include<fstream>
#include<string>

using namespace std;

#include"Contact.h"

Contact c;

int main()
{
    system("cls");
    fstream file_writer;
    file_writer.open("Contact_Book.dat",ios::out|ios::app|ios::binary);
    if(!file_writer.is_open())
    {
        std::cerr<<"\n Unable to open Contact_Book.dat \n";
        exit(8);
    }

    int ans;
    do
    {
        system("cls");
        c.inputContactDetails();
        file_writer.seekp(0,ios::end);
        file_writer.write((char *)&c,sizeof(c));

        cout<<"\n\n Do you want to Enter More contacts? : ";
        cin>>ans;
        cin.ignore(1024,'\n');
    }while(ans);

    file_writer.close();

    file_writer.open("Contact_Book.dat",ios::in|ios::binary);
    if(!file_writer.is_open())
    {
        std::cerr<<"\n Unable to open Contact_Book.dat \n";
        exit(8);
    }

    file_writer.seekg(0,ios::beg);
    while(file_writer.read((char *) &c,sizeof(c)))
    {
        c.displayContactDetails();
    }

    file_writer.close();

    remove("Contact_Book.dat");
    return 1;
}
Topic archived. No new replies allowed.