C Library - fsetpos() function



The C library fsetpos() function sets the file position of the given stream to the given position. The argument pos is a position given by the function fgetpos.This function is part of the <stdio.h> library and is particularly useful for random access to files.

Syntax

Following is the C library syntax of fsetpos() function −

int fsetpos(FILE *stream, const fpos_t *pos);

Parameter

This function accepts following parameters

  • FILE *stream: A pointer to a FILE object that identifies the stream.
  • const fpos_t *pos: A pointer to an fpos_t object containing the new position. The fpos_t type is used to represent file positions.

Return Value

The fsetpos() function returns 0 on success and returns a non-zero value on error.

Example 1

This example demonstrates setting the file position to the beginning of the file after writing to it.

#include <stdio.h>

int main() {
   FILE *file = fopen("example1.txt", "w+");
   if (file == NULL) {
      perror("Failed to open file");
      return 1;
   }

   fputs("Hello, World!", file);
   
   fpos_t pos;
   fgetpos(file, &pos);  // Get the current position

   rewind(file);  // Set position to the beginning
   fsetpos(file, &pos);  // Set back to the saved position

   fputs(" Overwrite", file);

   fclose(file);
   return 0;
}

Output

The above code produces following result−

Hello, World! Overwrite

Example 2

Using fsetpos()to Move to a Specific Position

This example demonstrates moving to a specific position in the file and modifying content.

#include <stdio.h>

int main() {
   FILE *file = fopen("example2.txt", "w+");
   if (file == NULL) {
      perror("Failed to open file");
      return 1;
   }

   fputs("1234567890", file);

   fpos_t pos;
   fgetpos(file, &pos);  // Get the current position

   pos.__pos = 5;  // Set position to 5
   fsetpos(file, &pos);  // Move to position 5

   fputs("ABCDE", file);

   fclose(file);
   return 0;
}

Output

After execution of above code, we get the following result

12345ABCDE

Example 3

Saving and Restoring File Positions

This example demonstrates saving a file position, performing some operations, and then restoring the original position.

#include <stdio.h>
int main() {
   FILE *file = fopen("example3.txt", "w+");
   if (file == NULL) {
      perror("Failed to open file");
      return 1;
   }

   fputs("Original content", file);

   fpos_t pos;
   fgetpos(file, &pos);  // Save the current position

   fseek(file, 0, SEEK_END);  // Move to the end of the file
   fputs("\nNew content", file);

   fsetpos(file, &pos);  // Restore the original position
   fputs(" modified", file);

   fclose(file);
   return 0;
}

Output

The output of the above code is as follows −

Original modified content
New content
Advertisements