Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

ungetc — pushing a character back onto a stream

ungetc pushes a character back for another input read without modifying the file. Portable code can rely on space for one character.

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

Syntax

#include <stdio.h>
int ungetc(int c, FILE *stream);

ungetc from <stdio.h> pushes c, converted to unsigned char, onto input stream stream. The next read retrieves it; it need not match a previously read character. The file remains unchanged.

It returns the pushed value or EOF on failure. Passing EOF fails without changing the stream. Store fgetc results in int, not char.

One character is guaranteed; further pushes may fail. Characters return in reverse order. Successful ungetc clears the end-of-file indicator. Successful fseek, fsetpos, or rewind discards pushback. This supports input lookahead, not general read rollback.

Examples

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

int main(void)
{
    FILE *stream = tmpfile();
    if (stream == NULL)
        return EXIT_FAILURE;

    if (fputs("AB", stream) == EOF || fseek(stream, 0L, SEEK_SET) != 0) {
        fclose(stream);
        return EXIT_FAILURE;
    }

    if (fgetc(stream) != 'A' || ungetc('X', stream) == EOF) {
        fclose(stream);
        return EXIT_FAILURE;
    }

    int first = fgetc(stream);
    int second = fgetc(stream);
    int close_result = fclose(stream);
    if (first != 'X' || second != 'B' || close_result == EOF)
        return EXIT_FAILURE;

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

Result

X B

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