C library functions -ungetc()

C Standard Library - <stdio.h>

Description

C Library Functionsint ungetc(int char, FILE *stream)Put characterchar(an unsigned character) pushed onto the specified streamstreamso that it is the next character to be read.

Declaration

Below is the declaration of the ungetc() function.

int ungetc(int char, FILE *stream)

Parameter

  • char-- This is the character to be pushed. This character is passed as its corresponding int value.
  • stream-- This is a pointer to a FILE object that identifies the input stream.

Return Value

If successful, it returns the pushed character; otherwise, it returns EOF, and the stream remains unchanged.

Example

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

Example

#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);
}

Suppose we have a text filefile.txt, whose content is as follows. The file will be used as input in the example:

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

Let us compile and run the above program, which will produce the following result:

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

C Standard Library - <stdio.h>

other extensions