c
  1. c-fseek

C fseek() Function

Syntax

int fseek(FILE *stream, long int offset, int whence);

Example

#include <stdio.h>

int main () {
   FILE *fp;
   char c;

   fp = fopen("file.txt","r");
   fseek(fp, 7, SEEK_SET);
   c = fgetc(fp);
   
   printf("The 8th character in file.txt is %c\n", c);
   fclose(fp);
   
   return 0;
}

Output

The output of the above example will be:

The 8th character in file.txt is H

Explanation

The C fseek() function is used to set the file position of the given file stream. The function takes three arguments:

  • stream: A pointer to the file stream that you want to set the position for.
  • offset: The number of bytes to offset from the position specified in the whence argument.
  • whence: The starting position for the offset.

The whence argument can take on one of three values:

  • SEEK_SET: The offset is relative to the beginning of the file.
  • SEEK_CUR: The offset is relative to the current file position.
  • SEEK_END: The offset is relative to the end of the file.

Use

The fseek() function is commonly used for positioning the file pointer to a specific location within a file. This is often used when seeking to a specific record in a text file or binary file. It is also useful for random access to data in large files.

Important Points

  • The fseek() function sets the file position indicator of the file stream to the given offset.
  • The whence argument specifies the starting position for the offset.
  • A positive offset seeks forward in the file, while a negative offset seeks backward in the file.
  • The fseek() function returns zero if successful, and a non-zero value otherwise.

Summary

The fseek() function in C is used to set the file position of the given file stream. It is commonly used for positioning the file pointer to a specific location within a file, which is useful for seeking to specific records in a text or binary file, or for random access to data in large files. The whence argument specifies the starting position for the offset, and the function returns zero if successful, and a non-zero value otherwise. Understanding the basic syntax and use cases for this function can greatly enhance your ability to work with files in C.

Published on: