C++ <cstdio> - fsetpos() Function
The C++ <cstdio> fsetpos() function sets the file position indicator and the multibyte parsing state (if any) for the file stream stream according to position represented by position, which is a pointer to an fpos_t object whose value is previously obtained by calling fgetpos() function.
A call to this function undoes the effects of ungetc() function and clears the end-of-file state, if it is set.
On streams open for update (read+write), a call to fsetpos() allows to switch between reading and writing. If a read or write error occurs, the error indicator ferror() for the stream is set.
Syntax
int fsetpos( FILE* stream, const fpos_t* position );
Parameters
stream |
Specify a pointer to a FILE object that identifies the stream. |
position |
Specify a pointer to a fpos_t object containing a position previously obtained by calling fgetpos() function. |
Return Value
On success, returns zero. On failure, returns non-zero value and sets errno to a system-specific positive value.
Example:
In the example below, program creates an empty file for output operations if the file test.txt does not exist. If the file already exists, its contents are discarded and the file is treated as a new empty file.
First, initial position of the file is get using fgetpos() function and then "Hello World!." is written to it. Then the position of the file is set to start using fsetpos() function to display the content of the file.
#include <cstdio> int main (){ //open the file in write and read mode FILE * pFile = fopen("test.txt","w+"); fpos_t position; int c; //get the beginning position fgetpos(pFile, &position); fputs("Hello World!.", pFile); //set the position to the start fsetpos(pFile, &position); //display the content of the file c = getc(pFile); while(c != EOF) { putchar(c); c = getc(pFile); } //close the file fclose (pFile); return 0; }
The output of the above code will be:
Hello World!.
❮ C++ <cstdio> Library