example4_random_access.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
41
42
#include <cstdio>
#include <cstdint>

int main() {
    FILE* file = fopen("random_access.bin", "wb+");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    // Write some integers to the file
    for (int i = 0; i < 10; ++i) {
        int32_t value = i * 10;
        fwrite(&value, sizeof(int32_t), 1, file);
    }

    // Move to a specific position and read
    fseek(file, 5 * sizeof(int32_t), SEEK_SET);
    int32_t value;
    fread(&value, sizeof(int32_t), 1, file);
    printf("Value at position 5: %d\n", value);

    // Move relative to current position and write
    fseek(file, sizeof(int32_t), SEEK_CUR);
    value = 999;
    fwrite(&value, sizeof(int32_t), 1, file);

    // Move to end and append
    fseek(file, 0, SEEK_END);
    value = 100;
    fwrite(&value, sizeof(int32_t), 1, file);

    // Read entire file
    rewind(file);
    while (fread(&value, sizeof(int32_t), 1, file) == 1) {
        printf("%d ", value);
    }
    printf("\n");

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