C Library Functions -fgetpos()

C Standard Library - <stdio.h>

Description

C Library Functionsint fgetpos(FILE *stream, fpos_t *pos)Get streamstreamthe current file position, and write it topos。

Declaration

Below is the declaration of the fgetpos() function.

int fgetpos(FILE *stream, 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.

Return Value

If successful, this function returns zero. If an error occurs, a nonzero value is returned.

Example

The following example demonstrates the usage of the fgetpos() 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("这将覆盖之前的内容", fp);
   fclose(fp);
   
   return(0);
}

Let us compile and run the above program, which will create a filefile.txt, whose content 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()The function is used to reset the write pointer to the beginning of the file and rewrite 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:

#include <stdio.h>

int main ()
{
   FILE *fp;
   int c;
   int n = 0;

   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