example3_binary_files.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
#include <cstdio>
#include <cstdint>

struct Record {
    int32_t id;
    char name[50];
    double balance;
};

int main() {
    Record records[] = {
        {1, "Alice", 1000.50},
        {2, "Bob", 2500.75},
        {3, "Charlie", 3750.25}
    };

    FILE* file = fopen("records.bin", "wb");
    if (file == NULL) {
        perror("Error opening file for writing");
        return 1;
    }

    fwrite(records, sizeof(Record), 3, file);
    fclose(file);

    file = fopen("records.bin", "rb");
    if (file == NULL) {
        perror("Error opening file for reading");
        return 1;
    }

    Record readRecord;
    while (fread(&readRecord, sizeof(Record), 1, file) == 1) {
        printf("ID: %d, Name: %s, Balance: %.2f\n", 
               readRecord.id, readRecord.name, readRecord.balance);
    }

    fclose(file);
    return 0;
}
Back to cstdio