Random access means you can move to any part of a file and read or write data from it without having to read through the entire file. There is no need to read each record sequentially if we want to access a particular record. C supports these functions for random access file processing.
Functions used for random access file are:
fseek()
ftell()
rewind()
fseek()
This function is used for seeking the pointer position in the file at the specified byte.
Syntax: fseek( file pointer, displacement, pointer position);
Where
->file pointer: It is the pointer that points to the file.
->displacement: It is positive or negative. This is the number of bytes that are skipped backward (if negative) or forward (if positive) from the current position. This is attached to L because this is a long integer.
Pointer position: This sets the pointer position in the file. SEEK_SET Seeks from the beginning of the file SEEK_CUR Seeks from the current position SEEK_END Seeks from the end of file
Equivalently,
Value
Pointer position
0
Beginning of file
1
Current position
2
End of file
fseek( p,10L,0) or fseek(fp,10L, SEEK_SET);
0 means pointer position is on the beginning of the file, from this statement pointer position is skipped 10 bytes from the beginning of the file.
fseek( p,5L,1) or fseek(fp,5L,SEEK_CUR);
1 means the current position of the pointer position. From this statement pointer position is skipped 5 bytes forward from the current position.
fseek(p,-5L,1) or fseek(fp,-5L,SEEK_CUR);
From this statement pointer position is skipped 5 bytes backward from the current position.