Use C ungetc function to put character back to the stream

Syntax

C ungetc function has the following syntax.

int ungetc(int ch, FILE *stream);

C ungetc function from header file stdio.h.

Description

C ungetc function puts the character ch back to the input stream.

This character will be obtained by the next read operation on stream.

C ungetc function returns ch on success or EOF on failure.

A call to fflush(), fseek(), or rewind() discards the character. You may not unget an EOF.

Example

Use C ungetc function to put the character back to stream.


#include <stdio.h>
/*from w  w  w  .j a  v a 2 s  .  co  m*/
int main ()
{
  FILE * fp;
  int c;
  char buffer [256];
  fp = fopen ("test.txt","rt");
 
  if (fp==NULL)
    perror ("Error opening file");
  else {
    while (!feof (fp))
    {
      c=getc (fp);
      if (c == '#')
        ungetc ('@',fp);
      else
        ungetc (c,fp);
      fgets (buffer,255,fp);
      fputs (buffer,stdout);
    }
  }

  return 0; 
}




















Home »
  C Language »
    Function Reference »




assert.h
ctype.h
math.h
setjmp.h
signal.h
stdio.h
stdlib.h
string.h
time.h
wctype.h