The function fsetpos () in C
The function int fsetpos (FILE * stream, const fpos_t * pos) in Library C sets the file location of the stream to the given location. The pos parameter is a location provided by the fgetpos function.
Declare function fsetpos () in C
Below is the declaration for the fsetpos () function in C:
int fsetpos ( FILE * stream , const fpos_t * pos )
Parameters
stream - This is the pointer to a FILE object that identifies the Stream.
pos - This is the pointer to an object fpos_t object containing a previously acquired location with the fgetpos function.
Returns the value
This function returns 0 if successful, or else it returns a nonzero value and sets the global variable errno to a positive value, which can be interpreted with perror.
For example
The following program C illustrates the usage of the fsetpos () function in C:
#include int main () { FILE * fp ; fpos_t position ; fp = fopen ( "baitapc.txt" , "w+" ); fgetpos ( fp , & position ); fputs ( "Hello, World!" , fp ); fsetpos ( fp , & position ); fputs ( "Dong nay se ghi de phan noi dung da co truoc do" , fp ); fclose ( fp ); return ( 0 ); }
Compiling and running the above program to create a baitcap.txt will have the following content. First we get the original location of the file using the fgetpos () function, and then we write Hello, World! in the file, then we use the fsetpos () function to restore the write pointer to the beginning of the file and then overwrite the file with the following content:
Now follow the contents of the above file by using the following C program:
#include int main () { FILE * fp ; int c ; fp = fopen ( "baitapc.txt" , "r" ); while ( 1 ) { c = fgetc ( fp ); if ( feof ( fp ) ) { break ; } printf ( "%c" , c ); } fclose ( fp ); return ( 0 ); }
Compiling and running the above C program will result:
According to Tutorialspoint
Previous article: Function fseek () in C
Next lesson: Function ftell () in C