ungetc – ungetc C Library Function

ungetc: 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 using ungetc function

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

ungetc C Library Function

#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");
      return(1);
   } else {
       fputs("TechCrashCourse#com", file);
       /*Setting file pointer position to first Character */
       fseek(file, 0, SEEK_SET);
        
       while(!feof(file)){
          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);
       }
       fclose(file);
   }
    
   return(0);
}

Output

TechCrashCourse.com