C Library Function - fgetpos()
C Standard Library - <stdio.h>
Description
The 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
Here is the declaration for the fgetpos() function.
int fgetpos(FILE *stream, fpos_t *pos)
Parameters
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
On success, the function returns zero. On error, it returns a non-zero value.
Example
The following example demonstrates the use 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("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, and finally, we use the fsetpos() function to reset the write pointer to the beginning of the file, overwriting 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;
int n = 0;
fp = fopen("file.txt","r");
while(1)
{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}