Advanced File Operations & Random Access
Basic file I/O runs sequentially: you read or write byte-by-byte from the beginning to the end. Advanced file operations allow you to jump to specific locations inside a file and read/write raw binary data blocks.
1. Binary block Read and Write
Instead of formatted text, binary I/O processes raw bytes directly from memory, which is faster and produces smaller files:
- fwrite(buffer, element_size, count, file): Writes a block of elements to file.
- fread(buffer, element_size, count, file): Reads a block of elements from file.
#include <stdio.h>
struct Point {
int x, y;
};
int main() {
struct Point p1 = {10, 20};
// Open in binary write mode
FILE *file = fopen("point.bin", "wb");
if (file != NULL) {
fwrite(&p1, sizeof(struct Point), 1, file);
fclose(file);
}
return 0;
}
2. Random Access: Jumping in Files
C maintains a "file position indicator" (cursor). You can query or move this cursor using three standard functions:
- fseek(file, offset, origin): Moves the file cursor.
- origin can be:
- SEEK_SET: Beginning of file.
- SEEK_CUR: Current cursor location.
- SEEK_END: End of file.
- ftell(file): Returns the current byte offset of the file cursor.
- rewind(file): Resets the cursor back to the beginning of the file.
Example: Reading arbitrary records
If we want to read the second point record inside a binary file without reading the first one:
#include <stdio.h>
#include <stdlib.h>
struct Point {
int x, y;
};
int main() {
FILE *file = fopen("point.bin", "rb");
if (file == NULL) return 1;
struct Point second_point;
// Seek to the start of the 2nd record (skip 1 sizeof(struct Point) bytes)
fseek(file, sizeof(struct Point), SEEK_SET);
// Query position indicator
long position = ftell(file);
printf("Reading from byte offset: %ld\n", position);
fread(&second_point, sizeof(struct Point), 1, file);
fclose(file);
return 0;
}