example3_binary_file_operations.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
#include <fstream>
#include <iostream>
#include <vector>

struct Person {
    char name[50];
    int age;
};

int main() {
    // Writing binary data
    std::vector<Person> people = {
        {"Alice", 30},
        {"Bob", 25},
        {"Charlie", 35}
    };

    std::ofstream outFile("people.bin", std::ios::binary);
    if (outFile.is_open()) {
        for (const auto& person : people) {
            outFile.write(reinterpret_cast<const char*>(&person), sizeof(Person));
        }
        outFile.close();
        std::cout << "Binary data written successfully." << std::endl;
    }

    // Reading binary data
    std::ifstream inFile("people.bin", std::ios::binary);
    if (inFile.is_open()) {
        Person person;
        while (inFile.read(reinterpret_cast<char*>(&person), sizeof(Person))) {
            std::cout << "Name: " << person.name << ", Age: " << person.age << std::endl;
        }
        inFile.close();
    }

    return 0;
}
Back to fstream