Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

rewind — return to the beginning of a file

rewind positions a stream at the beginning of its file and clears its error indicator. It returns no result, so it cannot directly report whether repositioning succeeded.

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

Syntax

#include <stdio.h>
void rewind(FILE *stream);

rewind(stream) from <stdio.h> positions an open FILE stream at the beginning of its file. Pass a valid pointer to an open stream, not NULL or a pointer used after fclose.

It acts like (void)fseek(stream, 0L, SEEK_SET), but also clears the error indicator. Successful repositioning also clears the end-of-file indicator and undoes ungetc effects. It does not erase file contents.

It returns void. When positioning failures must be detected, use fseek and check its result. Checking only ferror after rewind does not establish success. Do not assume every stream supports positioning.

Examples

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

int main(void)
{
    FILE *stream = tmpfile();
    if (stream == NULL) {
        return EXIT_FAILURE;
    }
    if (fputs("ABC", stream) == EOF || fflush(stream) == EOF) {
        fclose(stream);
        return EXIT_FAILURE;
    }

    rewind(stream);
    int first = fgetc(stream);
    if (first != 'A') {
        fclose(stream);
        return EXIT_FAILURE;
    }

    if (fclose(stream) == EOF) {
        return EXIT_FAILURE;
    }
    if (printf("first: %c\n", first) < 0) {
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

Result

first: A

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