fseek in c

fseek() in c

This fseek() is used for setting the file position indicator at the specified byte and any read or write operation on the file will be perform at the new position

Declaration:
int fseek(FILE *fptr,long displacement, int origin);

fptr: in above pointer to a FILE object that identifies the stream.
displacement: number of bytes to offset from position
origin: position from where offset is added.
returns: zero if successful, or else it returns a non-zero

Here fptr is a file pointer, displacement is a long integer which can be positive or negative and it denotes the number or collection of bytes that skipped forward (if this is positive) or skipped backward(if this is negative) specified in the third argument. so the argument is declared as long integer so it is possible to move in the large files In the function fseek(FILE *fptr,long displacement, int origin); the third argument which name is origin is a positive relative to which the displacement takes places it can take any one of three values

Constant value position
SEEK_SET 0 beginnging of file
SEEK_CURRENT 1 current position
SEEK_END 2 End of the file

The rewind(fptr) is equivalent to fseek(fptr,0L,0); and clearerr(fptr);

/* program to understand the fseek() */
#include<stdio.h>
#include<stdlib.h>
struct
Employee
{
char name[20];
int age;
float sallary;
}emp;
int main()
{
int n;
FILE *fptr;
fptr=fopen("myfile","rb");
if (fptr==NULL)
{
printf("Error when open file" );
}
printf("Enter any record number to read " );
scanf("%d", &n);
fseek(fptr,(n-1)*sizeof(emp),0); /* skip n-1 records */
fread(&emp,sizeof(emp),1,fptr); /* read the nth record */
printf("%s\n", emp.name);
printf("%d\n", emp.age);
printf("%f \n", emp.sallary);
fclose(fptr);
return 0;
}