CKTIS / C
fsetpos — C23 stream function
`fsetpos(stream, pos)` from `<stdio.h>` restores the file position indicator and the `mbstate_t` object, if any, from a value previously saved by a successful `fgetpos` on a stream associated with the same file. It returns `0` on success and a nonzero value on failure.
Version: C23
Syntax
int fsetpos(FILE *stream, const fpos_t *pos);fsetpos(stream, pos) from <stdio.h> restores the file position indicator and the mbstate_t object, if any, from a value previously saved by a successful fgetpos on a stream associated with the same file. It returns 0 on success and a nonzero value on failure.
The example writes ABCDE, saves the position after AB, reads to the end, and observes feof == 1. It then restores the saved state with fsetpos; output 1 0 C shows that EOF was cleared and C was read again from the intended position.
A successful call undoes effects of ungetc, clears the end-of-file indicator, and permits either input or output as the next operation on an update stream. fpos_t is opaque: do not perform arithmetic on it or transfer a value between different files. On a read or write failure the stream error indicator is set; the function returns nonzero and stores an implementation-defined positive value in errno.
Examples
#include <stdio.h>
int main(void){FILE *stream=tmpfile();if(!stream)return 1;if(fputs("ABCDE",stream)==EOF){fclose(stream);return 1;}rewind(stream);if(fgetc(stream)!='A'||fgetc(stream)!='B'){fclose(stream);return 1;}fpos_t pos;if(fgetpos(stream,&pos)!=0){fclose(stream);return 1;}while(fgetc(stream)!=EOF){}int before=feof(stream)!=0;if(fsetpos(stream,&pos)!=0){fclose(stream);return 1;}int after=feof(stream)!=0,character=fgetc(stream);printf("%d %d %c\n",before,after,character);return fclose(stream)==0?0:1;}
Result
1 0 C
The example writes `ABCDE`, saves the position after `AB`, reads to the end, and observes `feof == 1`. It then restores the saved state with `fsetpos`; output `1 0 C` shows that EOF was cleared and `C` was read again from the intended position.