#include <stdio.h> int ungetc(int c, FILE *f);
ungetc
to undo the effect of getc
. The ungetc
function backs up the file input pointer so that the next call to an input
routine returns c
. The call ungetc(EOF, f)
is valid but has no
effect.
For a binary file, a successful call to ungetc
moves the file position
back to the previous character, unless the file is positioned at the beginning.
ungetc
returns c
if its operation was successful or EOF
if
c
cannot be pushed back. You may not be able to push back more than a
single character, depending on the file contents and attributes.
ungetc
is limited to one character. Using
ungetc
to push back multiple characters without an intervening
read
is not portable.
ungetc
. Note that this operation
could be done more easily using scanf
:
#include <stdio.h> #include <ctype.h> int wordcnt = 0; static int skipspace(void); static int printword(void); main() { char line[80]; puts("Enter a short line of text:"); for(;;) { if (skipspace() == 0) break; /* Skip white space; stop at end of line. */ if (printword() == 0) /* Print the next word. */ break; } if (wordcnt == 0) puts("There were no words in that line.n"); exit(0); } static int skipspace(void) { /* Read white space characters from standard input. Use */ /* ungetc() to put back any nonwhite space character */ /* found. If a new line is read, stop reading and return 0. */ int ch; for (;;) { ch = getchar(); if (ch == EOF || ch == 'n') return 0; if (!isspace(ch)) break; } /* Put back nonspace for printword to read. */ ungetc(ch, stdin); return 1; } static int printword(void) { int ch; if (wordcnt == 0) puts("Words found in input:"); ++wordcnt; for(;;) { ch = getchar(); if (ch == EOF || ch == 'n') return 0; if (!isspace(ch)) putchar(ch); else return 1; } }
fgetc
, getc
Copyright (c) 1998 SAS Institute Inc. Cary, NC, USA. All rights reserved.