Pushes a character back onto the stream.
#include <stdio.h>
int ungetc( int c, FILE *stream );
c | Character to be pushed | |
stream | Pointer to FILE structure |
The ungetc function pushes the character c back onto stream and clears the end-of-file indicator. The stream must be open for reading. A subsequent read operation on the stream starts with c. An attempt to push EOF onto the stream using ungetc is ignored. The ungetc function returns an error value if nothing has yet been read from stream or if c cannot be pushed back.
Characters placed on the stream by ungetc may be erased if fflush, fseek, fsetpos, or rewind is called before the character is read from the stream. The file-position indicator will have the same value it had before the characters were pushed back. On a successful ungetc call against a text stream, the file-position indicator is unspecified until all the pushed-back characters are read or discarded. On each successful ungetc call against a binary stream, the file-position indicator is stepped down; if its value was 0 before a call, the value is undefined after the call.
Results are unpredictable if the ungetc function is called twice without a read operation between the two calls. After a call to the fscanf function, a call to ungetc may fail unless another read operation (such as the getc function) has been performed. This is because the fscanf function itself calls the ungetc function.
The ungetc function returns the character argument c. The return value EOF indicates a failure to push back the specified character.
Standards:ANSI, UNIX
16-Bit:DOS, QWIN, WIN, WIN DLL
32-Bit:DOS32X
/* UNGETC.C: This program first converts a character representation of an
* unsigned integer to an integer. If the program encounters a character
* that is not a digit, the program uses ungetc to replace it in the stream.
*/
#include <stdio.h>
#include <ctype.h>
void main( void )
{
int ch;
int result = 0;
printf( “Enter an integer: ” );
/* Read in and convert number: */
while( ((ch = getchar()) != EOF) && isdigit( ch ) )
result = result * 10 + ch - '0'; /* Use digit. */
if( ch != EOF )
ungetc( ch, stdin ); /* Put non-digit back. */
printf( “Number = %d\nNext character in stream = '%c'\n”,
result, getchar() );
}
Enter an integer: 521a
Number = 521
Next character in stream = 'a'