Introduction
fseek() and rewind() are the functions we use in file handling to manipulate the file pointer. There are some differences in both of them, and we will learn about those differences so that we can use both functions effectively.
So, let’s get started:
Recommended Topics, Sum of Digits in C and C Static Function.
fseek()
fseek() is the function that sets the file pointer at a specific position like at the beginning , end or at current position. fseek() consists of three parameters:
- pointer to file
- offset
- whence
It returns zero if successful, else non-zero.
Syntax
Below are the parameters explained:
- pointer - pointer to the file we are working on.
- Offset- it sets the number of bytes from the file pointer to read
-
Whence- whence sets the position of the pointer. Whence parameters is further divided into three categories:
SEEK_SET- sets the pointer at the beginning,
SEEK_END-sets the pointer at the end,
SEEK_CUR-sets the pointer to the current position of file pointer
Below is the source code to explain the working of fseek():
Time for an Example
#include <stdio.h>
#include<stdlib.h>
int main()
{
FILE *ptr;
/*reading the file using fopen method*/
ptr = fopen("test.txt","r");
if(ptr==NULL)
{
printf("file does not exist or file is invalid");
exit(0);
}
/*printing the current position of pointer*/
printf("current position of file pointer: %ld \n", ftell(ptr));
int result = fseek(ptr,5,SEEK_SET);
/*printing the position of pointer after applying fseek()*/
printf("position of file pointer after fseek: %ld \n", ftell(ptr));
if(result==0)
{
printf("fseek was successful");
}
return 0;
}
In the above code we check the position of the pointer before or after the fseek() function.
Output of the above code:
From the output we can evaluate that we can use the fseek() function to change the position of the pointer and then we can read the file from that particular position only.