Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

SEEK_SET, SEEK_CUR, SEEK_END — seek origins

The SEEK_SET, SEEK_CUR, and SEEK_END macros select the reference point for fseek: the beginning, current position, or end of the file.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <stdio.h>
int fseek(FILE *stream, long int offset, int whence);
/* whence: SEEK_SET, SEEK_CUR, SEEK_END */

These <stdio.h> macros have distinct integer values; do not assume particular numbers. The whence argument selects the base: SEEK_SET — file beginning, SEEK_CUR — current position, SEEK_END — file end.

For a binary stream, fseek adds offset to that base, measured in C bytes. Support for SEEK_END is not guaranteed even for binary streams. For a text stream, offset must be zero or come from an earlier successful ftell for the same file; the latter case requires SEEK_SET.

Check the result of fseek: zero means success; nonzero means failure.

Examples

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *f = tmpfile();
    int a, b;
    if (f == NULL) return EXIT_FAILURE;

    if (fputs("ABCDE", f) == EOF ||
        fseek(f, 1L, SEEK_SET) != 0) {
        fclose(f);
        return EXIT_FAILURE;
    }
    a = fgetc(f);
    if (a == EOF || fseek(f, 1L, SEEK_CUR) != 0) {
        fclose(f);
        return EXIT_FAILURE;
    }
    b = fgetc(f);
    if (b == EOF || fclose(f) != 0) return EXIT_FAILURE;

    if (printf("%c %c\n", a, b) < 0) return EXIT_FAILURE;
    return EXIT_SUCCESS;
}

Result

B D

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources