In C programming, files can be accessed in two main ways: sequential access and random access. Understanding the difference between these two methods is crucial for efficient file manipulation.
Sequential access means reading or writing data in a file in a linear order, from the beginning to the end. This is the simplest form of file access, where data is processed in the order it is stored.
#include <stdio.h>
int main() {
FILE *fp;
// Open a file for writing
fp = fopen("sequential.txt", "w");
if (fp == NULL) {
printf("Error opening file for writing!\n");
return 1;
}
// Write data sequentially
fprintf(fp, "Hello, World!\n");
fprintf(fp, "Sequential file access example.\n");
// Close the file
fclose(fp);
// Open the file for reading
fp = fopen("sequential.txt", "r");
if (fp == NULL) {
printf("Error opening file for reading!\n");
return 1;
}
// Read data sequentially
char buffer[100];
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}
// Close the file
fclose(fp);
return 0;
}
Random access allows reading or writing data at any position in the file without having to process data sequentially from the beginning. This is useful for applications where you need to frequently access different parts of the file.
#include <stdio.h>
int main() {
FILE *fp;
// Open a file for writing
fp = fopen("random.txt", "w+");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
// Write data at the beginning
fprintf(fp, "Random access example.\n");
// Move the file pointer to position 7 (0-based index)
fseek(fp, 7, SEEK_SET);
// Write data at the new position
fprintf(fp, "direct");
// Rewind to the beginning of the file
rewind(fp);
// Read data to verify the changes
char buffer[100];
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}
// Close the file
fclose(fp);
return 0;
}