Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

fgetpos — C23 stream function

`fgetpos(stream, pos)` from `<stdio.h>` stores an open stream’s current position state in the `fpos_t` object designated by `pos`. It returns zero on success and nonzero on failure; the saved state is intended for a later `fsetpos`.

Version: C23

Syntax

int fgetpos(FILE * restrict stream, fpos_t * restrict pos);

fgetpos(stream, pos) from <stdio.h> stores an open stream’s current position state in the fpos_t object designated by pos. It returns zero on success and nonzero on failure; the saved state is intended for a later fsetpos.

The example writes ABC, reads A, saves the position with fgetpos, reads B, restores the position with fsetpos, and reads B again. Output 1 B B demonstrates successful capture and restoration of the exact state.

fpos_t need not be an arithmetic type or a byte count; it can include multibyte parsing state, so do not perform arithmetic on it or serialize it as a portable offset. Both pointers must be valid and pos must remain alive until use. On failure the result is nonzero and the implementation stores a positive value in errno.

Examples

#include <stdio.h>

int main(void) {
    FILE *stream = tmpfile();
    if (stream == NULL) return 1;
    if (fputs("ABC", stream) == EOF) { fclose(stream); return 1; }
    rewind(stream);
    if (fgetc(stream) != 'A') { fclose(stream); return 1; }
    fpos_t position;
    int saved = fgetpos(stream, &position) == 0;
    int first = fgetc(stream);
    if (!saved || fsetpos(stream, &position) != 0) { fclose(stream); return 1; }
    int again = fgetc(stream);
    printf("%d %c %c\n", saved, first, again);
    return fclose(stream) == 0 ? 0 : 1;
}

Result

1 B B

The example writes `ABC`, reads `A`, saves the position with `fgetpos`, reads `B`, restores the position with `fsetpos`, and reads `B` again. Output `1 B B` demonstrates successful capture and restoration of the exact state.

Sources