Table of Contents

ungetc

#include <stdio.h> /* including standard library */
//#include <windows.h> /* uncomment this for Windows */
 
 int ungetc(int chr, FILE *stream);

Pushes chr (which must not be EOF), onto (input) stream stream such that it will be returned by the next read. Only one character of pushback is guaranteed (for each stream). Returns chr, or EOF on error.

C Sourcecode Example

/* 
 * ungetc example code
 * http://code-reference.com/c/stdio.h/ungetc 
 */
 
#include <stdio.h> /* including standard library */
//#include <windows.h> /* uncomment this for Windows */
 
 
int main(void)
{
   FILE *stream;
   int ch;
 
   stream = fopen("test.txt","w");
   fputs("Howdy, i write something into the test.txt file ",stream);
 
   if(stream == NULL) {
       perror("sorry but test.txt has");
     }
 
   freopen("test.txt","r",stream);
 
   while ((ch = getc(stream)) != EOF)
     {
        putc(ch, stdout);
        ch = getc(stream);
        ungetc(ch,stream); /* comment this out to see what happen */
     }
 
    printf("\n");
    return 0;
}

output

with ungetc
  user@host:~$ ./ungetc 
  Howdy, i write something into the test.txt file
without ungetc
  user@host:~$ ./ungetc 
  Hwy  rt oehn notets.x ie