Website Summary Files Commits Branches @commit @diff @stats
path: root / BinaryFiles / SaveStructsToBinaryFile.cpp
blob: 5e03b44669e34c1e8c082d18caef03549c7afd6e (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
#include <iostream>
#include <fstream>
using namespace std;

struct test
{
	char ch;
	int num;
};

int main()
{

	test obj1{ 'a', 4 };
	test obj2{ 'b', 5 };
	test obj3{ 'c', 6 };

	ofstream outF("Structs.bat", ios::binary);

	if (!outF.is_open())
	{
		cout << "Error while opening file"<<endl;
		return 1;
	}
	
	//запазваме 3-те обекта във файла
	outF.write((const char*)&obj1, sizeof(test));
	outF.write((const char*)&obj2, sizeof(test));
	outF.write((const char*)&obj3, sizeof(test));

	if (!outF.good()) // проверяваме дали след операцията потокът е в невалидено състояние
	{
		cout<<"Error occurred while writing the file";
		return 1;
	}
	
	outF.close();

	return 0;
}