C Language | Advanced Features | Random Access - fseek(), ftell()

Reading and writing data from the beginning of a file in order is called sequential access. Moving to an arbitrary position to read or write only the required part is called random access. This article explains random access with standard C functions.

Reading from an Arbitrary Position

File input normally progresses from beginning to end. As data is read, the position for the next operation advances automatically. The byte position used for the next read or write operation is called the file position.

Sequential access is efficient for ordinary text data. Binary files, however, often store several kinds of information in one file. If you need only a value at a specific byte position, reading every preceding byte is inefficient.

Use fseek() to move the file position.

fseek() Function

int fseek(FILE *stream, long offset, int origin);

stream is a valid file stream. offset is the number of bytes to move from origin.

Constant Meaning
SEEK_CUR Current file position
SEEK_SET Beginning of the file
SEEK_END End of the file

fseek() returns 0 on success and a nonzero value on failure.

Use ftell() to obtain the current file position.

ftell() Function

long ftell(FILE *stream);

Code 1

#include <stdio.h>

int main() {
 char fileName[256];
 int fileIndex , text;
 FILE *file;

 printf("Specify the file name>");
 scanf("%s" , fileName);
 printf("Specify the starting byte position.");
 scanf("%d" , &fileIndex);

 file = fopen(fileName , "rb");
 if (file == NULL) {
   fprintf(stderr , "A file operation error occurred.\n");
   return 0;
 }

 fseek(file , fileIndex , SEEK_SET);
 printf("Reading from file position %ld--\n" , ftell(file));

 while(1) {
   text = fgetc(file);
   if (feof(file)) break;
   printf("%c" , text);
 }

 printf("\n");
 fclose(file);
 return 0;
}

This program asks for a file name and a starting byte position. It moves from the beginning of the file by fileIndex bytes with SEEK_SET, then prints the remaining data as characters. Random access is particularly useful for binary data.