Website Summary Files Commits Branches @commit @diff @stats
path: root / Sem. 03 / students_staticName_to_binary.cpp
blob: 51fb711d1132907e2c814794cfc59c1128e6409c (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.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.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;
}