C Library Functions -fsetpos()

C Standard Library - <stdio.h>

Description

C Library Functionsint fsetpos(FILE *stream, const fpos_t *pos)Set the given streamstreamThe file position is the given position. Parametersposis the position given by the function fgetpos.

Declaration

Below is the declaration of the fsetpos() function.

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

Parameter

  • stream-- This is a pointer to a FILE object that identifies the stream.
  • pos-- This is a pointer to an fpos_t object that contains a position previously obtained with fgetpos.

Return Value

If successful, the function returns zero; otherwise, it returns a nonzero value and sets the global variableerrnoto a positive value, which can be interpreted via perror.

Example

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

Example

#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 us compile and run the above program, which will create a filefile.txt, the content of which is as follows. First we usefgetpos()The function obtains the initial position of the file, then we write to the fileHello, World!, then we usefsetpos()function to reset the write pointer to the beginning of the file, rewriting the file with the following content:

This will overwrite the previous content.

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

Example

#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>

other extensions