Name

ungetc

Synopsis

Pushes a character back onto a file buffer to be read next

#include <stdio.h>
intungetc( int c, FILE *fp );

The ungetc() function reverses the effect of a getc() call; it pushes the character c back onto the file buffer associated with the FILE pointer fp, so that c becomes the first character to be read in a subsequent read operation. (However, if the program successfully calls fseek(), fsetpos(), or rewind() before reading from the file again, then the pushed-back character is lost.) The ungetc() function does not change the file on disk.

You can push at least one character onto the file buffer with unget(). Multiple calls in succession are possible, but are not guaranteed to succeed without intervening read operations. If successive unget() calls succeed, the characters pushed will be read in last-in, first-out order.

If successful, the ungetc() function returns the character pushed back onto the file buffer, and clears the file’s EOF flag. On failure, ungetc() returns EOF. You cannot push an EOF value onto a file buffer.

The file associated with fp must be open for reading in either text or binary mode. If the file is in text mode, then ungetc() leaves the file access position indicator in an unspecified state until all pushed-back characters have been read again. If the file is in binary mode, ungetc() reduces the file position indicator by one. In either case, once all pushed-back characters have been read again, the file position indicator is the same as before ...

Get C in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.