blob: 5c9c77df9b32539b69a1afaadf97aed16d31fe29 (
plain) (
blame)
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
|
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
struct Student
{
char name[25];
int fn;
int age;
};
int main()
{
{ //write
Student st;
strcpy(st.name, "Ivan");
st.fn = 1234;
st.age = 33;
ofstream file("student.dat", ios::binary);
if (!file.open())
{
cout << "Error while writing to binary file!" << endl;
delete[] s1.name, s2.name;
return -1;
}
file.write((const char*)&st, sizeof(st)); //since the data is grouped in the struct, we can save it like this.
}
{ //read
Student st;
ifstream file("student.dat", ios::binary);
if (!file.open())
{
cout << "Error while reading from binary file!" << endl;
delete[] s1.name, s2.name;
return -1;
}
file.read((char*)&st, sizeof(st));
std::cout << st.name << " " << st.fn << " " << st.age << std::endl;
}
return 0;
}
|