C library function - ungetc()

Advertisements


Description

The C library function int ungetc(int char, FILE *stream) pushes the character char (an unsigned char) onto the specified stream so that the this is available for the next read operation.

Declaration

Following is the declaration for ungetc() function.

int ungetc(int char, FILE *stream)

Parameters

  • char -- This is the character to be put back. This is passed as its int promotion.

  • stream -- This is the pointer to a FILE object that identifies an input stream.

Return Value

If successful, it returns the character that was pushed back otherwise EOF is returned and the stream remains unchanged.

Example

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

#include <stdio.h>

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

   fp = fopen("file.txt", "r");
   if( fp == NULL ) 
   {
      perror("Error in 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, which contains the following data. This file will be used as an input for our example program:

this is tutorials point
!c standard library
!library functions and macros

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

this is tutorials point
+c standard library
+library functions and macros
+library functions and macros


Advertisements
Advertisements