blob: 569bcffb49ad04fb34734d64e02c72d05c57f451 (
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
|
#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.is_open())
{
cout << "Error while writing to binary file!" << endl;
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.is_open())
{
cout << "Error while reading from binary file!" << endl;
return -1;
}
file.read((char*)&st, sizeof(st));
std::cout << st.name << " " << st.fn << " " << st.age << std::endl;
}
return 0;
}
|