-
Notifications
You must be signed in to change notification settings - Fork 2
/
binaryIO.cpp
56 lines (42 loc) · 1008 Bytes
/
binaryIO.cpp
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
/*
* Basic example of read and write operations on binary files to store a struct
*
* @author J. Alvarez
*/
#include <iostream>
#include <fstream>
#pragma pack(push, 1)
struct Person {
char m_name[50];
int m_age;
double m_height;
};
#pragma pack(pop)
int main(int argc, char const *argv[])
{
Person person1 = {
"Pepe",
20,
1.55
};
std::ofstream output;
output.open("person.dat", std::ios::binary);
if(!output.is_open()) {
std::cout << "Could not open file to write" << std::endl;
return 1;
}
output.write(reinterpret_cast<char *>(&person1), sizeof(Person));
output.close();
Person person2;
std::ifstream input;
input.open("person.dat", std::ios::binary);
if(!input.is_open()) {
std::cout << "Could not open file to read" << std::endl;
return 1;
}
input.read(reinterpret_cast<char *>(&person2), sizeof(Person));
input.close();
std::cout << "I have read: " << person2.m_name << " - " << person2.m_age <<
" - " << person2.m_height << std::endl;
return 0;
}