fseek function in c

The fseek() function in C is used to set the file position indicator for a given file stream. It allows you to move the position indicator to a specific location within the file.

The syntax of the fseek() function is as follows:

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

Here, stream is a pointer to the file stream, offset is the number of bytes to offset from the origin, and origin specifies the point of reference for the offset.

The origin parameter can take one of the following values:

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

The fseek() function returns 0 if the operation is successful, and a non-zero value otherwise.

Here's an example that demonstrates the usage of fseek():

#include <stdio.h>

int main() {
   FILE *file;
   char ch;

   file = fopen("example.txt", "r");
   if (file == NULL) {
       printf("Unable to open file.\n");
       return 1;
   }

   // Move the position indicator to the 10th byte from the beginning of the file
   fseek(file, 10, SEEK_SET);

   // Read and print the character at the current position
   ch = fgetc(file);
   printf("Character at position 10: %c\n", ch);

   fclose(file);
   return 0;
}

In this example, the program opens a file named "example.txt" in read mode. It then uses fseek() to move the position indicator to the 10th byte from the beginning of the file. Finally, it reads and prints the character at the current position (which should be the 10th character in the file).

Remember to include the <stdio.h> header file to use the fseek() function.