Latest web development tutorials

C library functions - ungetc ()

C standard library - <stdio.h> C standard library - <stdio.h>

description

C library functionsint ungetc (int char, FILE * stream) The character char (anunsigned character) is pushed into the specified streamstreamso that it is next to be read into the characters.

statement

Here is ungetc () function's declaration.

int ungetc(int char, FILE *stream)

parameter

  • char - which is to be pushed into the characters.The character of its corresponding int value passed.
  • stream - This is a pointer to FILE pointer to an object, the object identifier FILE input stream.

return value

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

Examples

The following example demonstrates ungetc () function is used.

#include <stdio.h>

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

   fp = fopen("file.txt", "r");
   if( fp == NULL ) 
   {
      perror("打开文件时发生错误");
      return(-1);
   }
   while(!feof(fp)) 
   {
      c = getc (fp);
      /* 把 ! 替换为 + */
      if( c == '!' ) 
      {
         ungetc ('+', fp);
      }
      else 
      {
         ungetc(c, fp);
      }
      fgets(buffer, 255, fp);
      fputs(buffer, stdout);
   }
   return(0);
}

Suppose we have a text filefile.txt, it reads as follows.As an example of the file, enter:

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

Let's compile and run the above program, which will result in the following:

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

C standard library - <stdio.h> C standard library - <stdio.h>