I/O opertaions binary

its a code which outputs data into a file in binary than reads from it.
first time it works fine, but on second run there is some run time error.
basically on second run its not reading correctly from the file.
Any help will be appreciated. Thanks

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

struct person
{
    string name{""};
    int age{0};
    string sex{""};
};

int main()
{
    vector<person> v;
    vector<person> v1;
    person p;

    {
        p.name="adam";
        p.age=22;
        p.sex="male";
        v.push_back(p);
    }
    {
        p.name="shaun";
        p.age=23;
        p.sex="male";
        v.push_back(p);
    }
    {
        p.name="megan";
        p.age=24;
        p.sex="female";
        v.push_back(p);
    }

    
    ofstream os("record.dat",ios_base::binary|ios_base::app);

    for(int i=0;i<v.size();++i)
    {
        os.write((char*) &v[i],sizeof(p));
    }
    os.close();



    ifstream is("record.dat",ios_base::binary);

    if(!is) cout<<"file not found";


    while(is.read((char*)&p,sizeof(p)))
    {
        v1.push_back(p);
    }
    is.close();

    for(auto a:v1)
    {
        cout<<a.name<<" "<<a.age<<" "<<a.sex<<endl;
    }


    return 0;
}
You cannot write a struct containing complex objects like std::string like that. It will write some pointers and other stuff that std::string uses not the data itself.

So either your struct person entirely consists of primitive type like char array or better yet you use the stream operators >> <<.
Topic archived. No new replies allowed.