Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C library function - fgetpos()

C library function - fgetpos()

C Standard Library - <stdio.h> C Standard Library -

Description

C library function **int fgetpos(FILE stream, fpos_t pos) gets the current file position of the stream stream and writes it to pos.

Declaration

The following is the declaration of the fgetpos() function.



int fgetpos(FILE *stream, fpos_t *pos)

Parameters

Return Value

If successful, the function returns zero. If an error occurs, it returns a nonzero value.

Example

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



#include 



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 program above, which will create a file file.txt, whose content is as follows. First we use the fgetpos() function to get the initial position of the file, then we write to the file Hello, World!, then we use fsetpos() function to reset the write pointer to the beginning of the file and rewrite the file with the following content:



这将覆盖之前的内容

Now let us use the following program to view the content of the file above:



#include 



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> C Standard Library -