Sequential vs random access concepts
What you'll learn: The fundamental difference between reading a file from start to finish versus jumping directly to specific locations.
The VHS vs. the DVD
Think of file access like watching a movie on two different types of media.
Sequential access is like an old VHS tape. If you want to watch the scene at the 60-minute mark, you have to hit "Fast Forward" and physically pass through every inch of tape from the beginning until you reach your spot. In C, most basic file functions (like fgets or fprintf) work this way. Each time you read a line, a "file pointer" moves forward, and the next read starts exactly where the last one ended.
Random access is like a DVD or a digital stream. If you want to see Chapter 5, you click a button and jump there instantly. You don't need to process Chapters 1 through 4 to get there. In C, we use specific functions to move the "playback head" to any byte position we want, allowing us to read or write data out of order.
How it looks in C
By default, C treats files like a stream of water—you deal with what comes out of the pipe next. However, the standard library gives us tools to manipulate our position within that stream.
#include <stdio.h>
int main() {
FILE *fptr = fopen("data.txt", "r");
// 1. Sequential Access: Reading naturally
char buffer[100];
fgets(buffer, 100, fptr); // Reads the first line
fgets(buffer, 100, fptr); // Reads the second line automatically
// 2. Random Access: Jumping around
// fseek moves the "cursor" to the 50th byte from the start
fseek(fptr, 50, SEEK_SET);
// Now, the next read happens at byte 50, skipping everything before it!
fgets(buffer, 100, fptr);
fclose(fptr);
return 0;
}
When to use each
You use sequential access for most tasks, such as reading a configuration file or processing a list of names. It is simple and predictable.
You use random access for large databases or complex file formats. If you have a file containing 1 million employee records and you only need the 500,000th one, random access allows you to jump straight to that record's address without wasting time reading the first 499,999 entries.
Key takeaway
Sequential access processes data in a continuous line, while random access allows you to jump to any specific byte instantly.