fseek function in c – fseek : library function

fseek function in c: The function int fseek(FILE *stream, long int offset, int where); sets the position indicator of the stream to a new position. The new position is defined by adding offset to a reference position specified by where. The value of where should be one of the following constants defined in stdio.h header file.

Constant Description
SEEK_SET Beginning of file
SEEK_END End of file
SEEK_CUR Current position of the file pointer

Function prototype of fseek

int fseek(FILE *stream, long int offset, int where);
  • stream : This is a pointer to a FILE object which identifies a stream.
  • offset : This is the number of bytes to offset from where.
  • where : This is the position from where offset is added to set new position of file position indicator.

Return value of fseek

This function returns a zero on success otherwise it returns a non-zero value.

C program using fseek function

The following program shows the use of fseek function to set the file position indicator to 4th position instead of starting from 0th position.

fseek : <stdio.h> library function

#include <stdio.h>
 
int main(){
   FILE *file;
   int ch;
    
   /* Open a file for reading */
   file = fopen("textFile.txt","w+");
   if(file == NULL){
      perror("Error: Unable to open a file");
      return(1);
   } else {
       fputs("TechCrashCourse.com", file);
       /*Setting file pointer position to 5th Character */
       fseek(file, 4, SEEK_SET);
       /* It will skip first four characters */
       while(!feof(file)){
          ch = fgetc(file);
          printf("%c", ch);
       }
       fclose(file);
   }
    
   return(0);
}
</stdio.h>

Output

CrashCourse.com