Welcome to our comprehensive guide on Random File Access in C Programming! This lesson is designed for both beginners and intermediate learners, and we'll walk you through this fascinating topic step by step. 📝
Before diving into Random File Access, let's briefly discuss file access in C. There are two types of file access:
In this lesson, we'll focus on Direct Access, also known as Random Access.
Random File Access allows us to read or write data at any specific location (or record) within a file, not necessarily from the beginning. This is achieved using the fseek() and ftell() functions in C.
fseek() Function 💡fseek() is used to move the file position indicator (a pointer that points to the current position in the file) to a specific location within the file.
int fseek(FILE *stream, long int offset, int whence);stream: Pointer to the file streamoffset: The number of bytes to move the file position indicatorwhence: Indicates where the offset should be counted from (SEE BELOW)The whence argument can take three values:
SEEK_SET: Move the file position indicator to the beginning of the fileSEEK_CUR: Move the file position indicator from the current positionSEEK_END: Move the file position indicator to the end of the fileftell() Function 💡ftell() returns the current position of the file position indicator. It can be used to save the current position in the file for later use.
long int ftell(FILE *stream);stream: Pointer to the file streamLet's create a simple program to understand Random File Access. This program will write some data to a file, move the file position indicator to a specific location, and then read the data from that position.
#include <stdio.h>
int main() {
FILE *file;
char data[] = "Hello, World!";
long int position;
// Create a file named 'test.txt'
file = fopen("test.txt", "w");
if (file == NULL) {
printf("Error: Could not open file.\n");
return 1;
}
// Write data to the file
fputs(data, file);
// Move the file position indicator to the beginning
rewind(file);
// Save the current position
position = ftell(file);
// Move the file position indicator to the fifth character
fseek(file, position + 5, SEEK_SET);
// Read the data from the new position
char read_data[6];
fread(read_data, 1, 6, file);
read_data[6] = '\0';
printf("Data after the fifth character: %s\n", read_data);
// Close the file
fclose(file);
return 0;
}This program creates a file named test.txt, writes "Hello, World!", moves the file position indicator to the fifth character, and reads the remaining data.
What does the `fseek()` function do in C?
That's all for this lesson on Random File Access in C Programming! Stay tuned for more engaging and informative lessons on C and other programming languages here at CodeYourCraft. 💡 Happy coding!