int  ungetc ( int character , FILE * stream );

Push a character back into stream.
  A character is pushed into an input stream where last character was read and the file pointer is reset to that previous position. This character will be returned by the next call to getc or fread for the same stream.
  If the End-Of-File indicator was set is cleared after a call to this function.
  A call to fflush, fseek, fsetpos or rewind for this stream will undo the effects of any previous call to ungetc.
  This function do not affect the file associated with the stream, which will remain unchanged by any call to this function.


character to be pushed.
pointer to an open file.

Return Value.
  If successful, the character putted is returned.
  Otherwise EOF is returned and the stream remains unchanged.

  Defined in ANSI-C.


/* ungetc example */
#include <stdio.h>

main ()
  FILE * pFile;
  char c;
  char buffer [256];
  pFile = fopen ("myfile.txt","rt");
  if (pFile==NULL) perror ("Error opening file");
  else {
    while (!feof (pFile))
      c=fgetc (pFile);
      ungetc (pFile)
      fgets (buffer,255,pFile);
      printf ("[%c] %s",c,buffer);

  return 0;  
This example opens an existing file called myfile.txt and reads the first character of every line, then pushes back this character into the stream and gets the whole line into buffer.
[T] This is a sample file
[c] called myfile.txt

See also.
  getc, fgetc, putc

© The C++ Resources Network, 2000