fseek in c is important function in file handling.
In this tutorial, we are going to learn what is fseek in c, how to use fseek function,why fseek function is used and it’s example.
The file is a collection of data i.e file contains large amount of data. In file if you want to access particular data present in file one you can do is to iterate loop till end to get that data from file.
But a problem with this option is,
- You have to iterate loop till end.
- Requires lot of time.
- Also increase the complexity.
- Requires more memory.
Instead of using this option another easy method is to use the fseek function.
As name implies fseek function seeks cursor to position.
fseek function:- fseek function seeks (moves) cursor to the position in file.
if you want to access data from anywhere in file you can move pointer cursor using fseek function and access.
syntax for fseek function:-
fseek (FILE *fp ,int offset ,int whence);
In above syntax, given the syntax for using fseek function which accepts 3 parameter which are as follows
- First is FILE *fp :- This parameter is the pointer to file.
- int offset :- This parameter is the position of data which we want to find or accept .
- int whence :- This parameter tells position where offset starts.
Different whence in fseek function which are as follows
Consider file with content:-
1. fseek (fp,0,SEEK_END);
In above example the fseek will point to end of file
In above example the fseek will start from start
fseek program in c
void main ()
fp=fopen("technical.txt","r");. // Opening file in read mode
printf ("\n File seek");
fseek(fp,0,SEEK_END);. //seeking file
printf ("\n character at end of file =%c",ch);
printf ("\n character from start = %c",ch);
printf("\n character from current position=%c",ch);
Output:-. (file technical.txt file with content:- Technical seek)
- In above program we seek position to access character.
- First we open file in read mode.
- Let us assume technical.txt file exists at location with content (content:- Technical seek) and opened successfully by fopen function.
- We use fseek function to seek in file which accepts 3 parameter.first is file pointer , a pointer which points to file. Second is offset and third is the whence i.e where to start positioning in file.
- Using fseek function fseek(fp,0,SEEK_END) we position cursor at end of file and access the 0 character.
- We get the character which pointer points using fgetc function.
- Similarly we use different whence to seek and access character file.