What is the ungetc() Function in C?

What is ungetc()?

The ungetc() function is part of the C standard library and is declared in the header. It enables you to push a single character back onto an input stream, effectively “unreading” it. This character will then be returned by the next read operation on that stream.​

Syntax of ungetc()

int ungetc(int ch, FILE *stream);
  • ch → Character to be pushed back (converted to unsigned char)
  • stream → Input stream (must be open for reading)
  • Returns: On success, returns the character pushed back. On failure, returns EOF.

Key Characteristics of ungetc() Function

  • You can only push back one character in some implementations. Pushing back multiple characters may not work reliably.
  • ungetc() only works on input streams, not output streams.
  • The pushed-back character will be the next character read by functions like getc() or fgetc().
  • ungetc() does not change the file position indicator.

Example of ungetc() Function

Example 1:

#include <stdio.h>
 
int main() {
    FILE *quizFile;
    int mcqChar;
 
    // Open file in read mode
    quizFile = fopen("mcqdata.txt", "r");
    if (quizFile == NULL) {
        printf("Unable to open 'mcqdata.txt' for reading quiz data.\n");
        return 1;
    }
 
    // Read first character from the file
    mcqChar = fgetc(quizFile);
    printf("First character read from MCQ file: %c\n", mcqChar);
 
    // Push it back to the stream
    if (ungetc(mcqChar, quizFile) == EOF) {
        printf("Failed to push character back into the stream.\n");
        fclose(quizFile);
        return 1;
    }
 
    // Re-read the same character
    int quizChar = fgetc(quizFile);
    printf("Character read again after ungetc(): %c\n", quizChar);
 
    fclose(quizFile);
    return 0;
}

Here’s the expected output for the ungetc() example, assuming mcqdata.txt contains the following content:

advertisement
Sanfoundry MCQs are helpful!

Program Output

First character read from MCQ file: S
Character read again after ungetc(): S

This C program shows how to use the ungetc() function to put a character back into a file stream. It opens a file called mcqdata.txt and reads the first character, which is ‘S’ in this case. Then, it uses ungetc() to push the character back. When it reads again, it gets the same character ‘S’. This proves that ungetc() works. The program is useful when you want to “peek” at a character but still need to read it again later.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

Example 2:

#include <stdio.h>
 
int main()
{
    int mcqInput;
 
    printf("Sanfoundry Quiz - Enter a character: ");
    mcqInput = getchar();
 
    // Push the character back into stdin
    ungetc(mcqInput, stdin);
 
    // Read the character again
    int reRead = getchar();
 
    printf("Character re-read from input stream: %c\n", reRead);
 
    return 0;
}

Sample Output

Sanfoundry Quiz - Enter a character: A
Character re-read from input stream: A

This C program shows how ungetc() works with keyboard input. It first asks the user to enter a character using getchar(). Then, it pushes that character back into the input stream with ungetc(). After that, it reads the same character again using getchar() and prints it. This confirms that you can read the same character again after putting it back.

Limitations and Considerations

  • Buffer Size: Only one character is guaranteed to be pushed back onto the stream. Attempting to push back multiple characters without intervening reads may fail.
  • Binary vs. Text Streams: The behavior of ungetc() can differ between binary and text streams, especially concerning the file position indicator.
  • Thread Safety: When working with multithreaded applications, ensure proper synchronization when using ungetc() to avoid race conditions.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

advertisement

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.