#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;
}