0
0
CHow-ToBeginner · 3 min read

How to Use ungetc in C: Syntax, Example, and Tips

In C, ungetc pushes a character back onto an input stream so it can be read again. You call ungetc(character, stream) after reading from the stream to 'un-read' a character, which will be returned by the next read operation.
📐

Syntax

The ungetc function has this syntax:

  • int ungetc(int character, FILE *stream);

Here, character is the character you want to push back, and stream is the input stream (like stdin or a file pointer).

If successful, ungetc returns the character pushed back; otherwise, it returns EOF.

c
int ungetc(int character, FILE *stream);
💻

Example

This example reads a character from standard input, pushes it back using ungetc, then reads it again to show it was returned to the stream.

c
#include <stdio.h>

int main() {
    int ch;
    printf("Enter a character: ");
    ch = getchar();

    printf("You entered: %c\n", ch);

    // Push the character back to the input stream
    if (ungetc(ch, stdin) == EOF) {
        printf("Failed to push character back.\n");
        return 1;
    }

    // Read the character again
    int ch2 = getchar();
    printf("Character read again after ungetc: %c\n", ch2);

    return 0;
}
Output
Enter a character: A You entered: A Character read again after ungetc: A
⚠️

Common Pitfalls

  • Only one character can be pushed back reliably: Multiple calls to ungetc without reading in between may fail.
  • Character must be representable as unsigned char or EOF: Passing invalid values can cause undefined behavior.
  • Do not use ungetc on output streams: It only works on input streams.
  • Check return value: Always verify ungetc did not return EOF to ensure success.
c
/* Wrong way: pushing multiple characters without reading */

#include <stdio.h>

int main() {
    int ch1 = 'A';
    int ch2 = 'B';

    if (ungetc(ch1, stdin) == EOF) {
        printf("Failed to push ch1\n");
    }
    if (ungetc(ch2, stdin) == EOF) {
        printf("Failed to push ch2\n");
    }

    // Only ch2 is guaranteed to be read next
    printf("Next char: %c\n", getchar());
    printf("Next char: %c\n", getchar());

    return 0;
}
Output
Failed to push ch2 Next char: B Next char: A
📊

Quick Reference

ungetc Cheat Sheet:

FunctionDescriptionReturn Value
ungetc(character, stream)Pushes character back to input streamCharacter pushed or EOF on failure
getchar()Reads next character from stdinCharacter read or EOF
EOFEnd-of-file indicator-1

Key Takeaways

Use ungetc to push one character back onto an input stream for re-reading.
Always check if ungetc returns EOF to confirm success.
ungetc only works on input streams, not output streams.
Avoid pushing multiple characters back without reading in between.
The pushed back character will be returned by the next read operation.