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

struct Record {
    int id;
    char name[20];
    double score;
};

int main() {
    std::vector<Record> records = {
        {1, "Alice", 95.5},
        {2, "Bob", 87.3},
        {3, "Charlie", 91.8}
    };

    std::ofstream outFile("records.bin", std::ios::binary);
    
    if (outFile.is_open()) {
        for (const auto& record : records) {
            outFile.write(reinterpret_cast<const char*>(&record), sizeof(Record));
        }
        outFile.close();
        std::cout << "Successfully wrote binary data to the file." << std::endl;
    } else {
        std::cerr << "Unable to open file" << std::endl;
    }

    return 0;
}
Back to ofstream