Easy Tutorial
❮ C Examples Standard Deviation C Standard Library Math H ❯

C Library Function - ungetc()

C Standard Library - <stdio.h>

Description

The C library function int ungetc(int char, FILE *stream) pushes the character char (an unsigned character) back into the specified stream stream so that it is the next character read.

Declaration

Here is the declaration for the ungetc() function.

int ungetc(int char, FILE *stream)

Parameters

Return Value

On success, it returns the character pushed back, otherwise it returns EOF and the stream remains unchanged.

Example

The following example demonstrates the use of the ungetc() function.

#include <stdio.h>

int main ()
{
   FILE *fp;
   int c;
   char buffer [256];

   fp = fopen("file.txt", "r");
   if( fp == NULL ) 
   {
      perror("Error opening file");
      return(-1);
   }
   while(!feof(fp)) 
   {
      c = getc (fp);
      /* Replace ! with + */
      if( c == '!' ) 
      {
         ungetc ('+', fp);
      }
      else 
      {
         ungetc(c, fp);
      }
      fgets(buffer, 255, fp);
      fputs(buffer, stdout);
   }
   return(0);
}

Assuming we have a text file file.txt with the following content, which will be used as input in the example:

this is tutorialpro
!c standard library
!library functions and macros

Compiling and running the above program will produce the following result:

this is tutorialpro
+c standard library
+library functions and macros

C Standard Library - <stdio.h>

❮ C Examples Standard Deviation C Standard Library Math H ❯