I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com


Un-get character from input stream
+ View other versions (4)


#include <stdio.h>
int ungetc (int c, FILE *stream)


The ungetc function pushes the character c (converted to an unsigned char) back onto the input stream pointed to by stream. The pushed-back characters will be returned by subsequent reads on the stream (in reverse order). A successful intervening call, using the same stream, to one of the file positioning functions (reference:fseek) will discard the pushed back characters.

One character of push-back is guaranteed, but as long as there is sufficient memory, an effectively infinite amount of pushback is allowed.

If a character is successfully pushed-back, the end-of-file indicator for the stream is cleared. The file-position indicator is decremented by each successful call to ungetc. If its value was 0 before a call, its value is unspecified after the call.

The following code counts the number of occurences of the word "bla" in the text file "fred.txt". It uses the ungetc function to achieve this.

Example 1

#include <stdio.h>
#include <string.h>
int main()
  FILE *f;
  if (f = fopen("fred.txt", "rt"))
    int blas = 0;
    while (!feof(f))
      char c = getc(f);
      if (c == 'b')
        ungetc(c, f);
        char tmp[4];
        for (int i = 0; i < 3; ++i)
          tmp[i] = getc(f);
        tmp[3] = 0;
        if (!strcmp(tmp, "bla"))
    printf("Number of bla's: %d\n", blas);
  return 0;

Return Values

The ungetc function returns the character pushed-back after the conversion, or <span class="Dv">EOF</span> if the operation fails. If the value of the argument \c c character equals <span class="Dv">EOF</span>, the operation will fail and the stream will remain unchanged.