ungetc
Un-get character from input stream
Description
The ungetc function pushes the characterc
(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")) ++blas; } } fclose(f); printf("Number of bla's: %d\n", blas); } return 0; }