Easy Tutorial
❮ C Examples Array Largest Element C Function Fputc ❯

C Library Function - fsetpos()

C Standard Library - <stdio.h>

Description

The C library function int fsetpos(FILE *stream, const fpos_t *pos) sets the file position of the given stream stream to the position given by pos. The parameter pos is a position given by the function fgetpos.

Declaration

Here is the declaration for the fsetpos() function.

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

Parameters

Return Value

On success, the function returns zero. On failure, it returns a non-zero value and sets the global variable errno to a positive value that can be interpreted by perror.

Example

The following example demonstrates the use of the fsetpos() function.

#include <stdio.h>

int main ()
{
   FILE *fp;
   fpos_t position;

   fp = fopen("file.txt","w+");
   fgetpos(fp, &position);
   fputs("Hello, World!", fp);

   fsetpos(fp, &position);
   fputs("This will overwrite the previous content", fp);
   fclose(fp);

   return(0);
}

Let's compile and run the above program, which will create a file file.txt with the following content. Initially, we use the fgetpos() function to get the initial position of the file, then we write Hello, World! to the file. Next, we use the fsetpos() function to reset the write pointer to the beginning of the file and overwrite the file with the following content:

This will overwrite the previous content

Now, let's use the following program to view the content of the above file:

#include <stdio.h>

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

   fp = fopen("file.txt","r");
   while(1)
   {
      c = fgetc(fp);
      if( feof(fp) )
      {
          break ;
      }
      printf("%c", c);
   }
   fclose(fp);
   return(0);
}

C Standard Library - <stdio.h>

❮ C Examples Array Largest Element C Function Fputc ❯