example3_reading_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
32
#include <iostream>
#include <fstream>
#include <vector>

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

int main() {
    std::ifstream file("records.bin", std::ios::binary);
    
    if (file.is_open()) {
        Record record;
        std::vector<Record> records;

        while (file.read(reinterpret_cast<char*>(&record), sizeof(Record))) {
            records.push_back(record);
        }

        file.close();

        for (const auto& r : records) {
            std::cout << "ID: " << r.id << ", Name: " << r.name << ", Score: " << r.score << std::endl;
        }
    } else {
        std::cerr << "Unable to open file" << std::endl;
    }

    return 0;
}
Back to ifstream