fseek
is a function in the C library that allows the user to set the file pointer at a specific offset.
Below is the declaration for fseek
:
fp: The pointer to the FILE object that you intend to access.
offset: The number of bytes to offset from the whence position.
whence: The position at which the file object is accessed and the point from which the offset is added. The whence position can be specified using the following 3 constants:
SEEK_SET – Places file pointer at the beginning of the file.
SEEK_CUR – Places file pointer at a given position.
SEEK_END – Places file pointer at the end of file.
The fseek
function returns zero if it executes without error. Otherwise, it returns a non-zero value.
In the following example, we open a text file (placed in the same directory) and print everything after the first word, “hello”:
#include <stdio.h>// function that prints from the file pointer til// the end of filevoid print_onwards(FILE* myfile){int i;while( (i = fgetc(myfile)) != EOF)putchar(i);}int main(){FILE *myfile;myfile = fopen("myFile.txt", "r");// Placing file pointer after hello// (5 characters == 5 bytes)fseek(myfile, 5, SEEK_SET);print_onwards(myfile);return 0;}
In the example above, we placed the file pointer myfile at an offset of 5 bytes from the SEEK_SET position. This means we skipped the first 5 characters of “Hello”. We then printed the file from the position of the file pointer until the end of the file using the print_onwards function.
Free Resources