ungetc : <stdio.h> library function

The function int ungetc(int char, FILE *stream); pushes the character 'char' onto the given stream so that char is available for the next read operation form the stream. After pushing the character it decreases its internal file position.

Function prototype of ungetc

int ungetc(int char, FILE *stream);
  • char : This is the character to be pushed back in stream. This is passed as integer promotion of character.
  • stream : A pointer to a FILE object which identifies an input stream.

Return value of ungetc

On success, this function returns the character to be put back in stream otherwise EOF is returned, in case of failure.

C program to show the use of ungetc function

The following program shows the use of ungetc function to push a character back to input stream.

#include <stdio.h>

int main(){
   FILE *file;
   int ch;
   /* Creating a new file */
   file = fopen("textFile.txt","w+");
   if(file == NULL){
      perror("Error: Unable to open a file");
   } else {
       fputs("TechCrashCourse#com", file);
       /*Setting file pointer position to first Character */
       fseek(file, 0, SEEK_SET);
          ch = getc(file);
          /* Replacing '#' with '.' */
          if(ch == '#'){
              ungetc('.', file);
          } else {
              ungetc(ch, file);
          /* Fetch the character again from file */
          ch = getc(file);
          printf("%c", ch);

Program Output