C Programming/C Reference/stdio.h/ungetc
||A Wikibookian suggests that this book or chapter be merged into C file input/output.
Please discuss whether or not this merge should happen on the discussion page.
Ungetc is a version of a C standard library function ungetch. It is somewhat a restricted function.
int ungetc (int c, FILE *stream)
Here, c is a character variable, stream is a file pointer and the overall function is expressed in integer data type.
As mentioned above, rather it is a restricted version of ungetch, the function pushes the character specified by the value of c. At the time of pushing, the character c is converted to a unsigned char and then pushed to the input stream. The pushed character can be returned back if a getc function is applied to the stream.
A single push back of the character is allowed at a call. Trying to do a push back in a succession may or may not work properly. In normal and usual practices, 4 times the function is called and hence 4 characters are pushed consecutively. It means that the process of this function is totally machine dependent. Hence if memory is large in extent in a machine then there is a possibility to have the push backs for infinitly large times.
The characters which are pushed back are returned by any subsequent read on the stream (in reverse order) and if the input from the stream is buffered, it means that the last character pushed will be returned first. When a normal push back of the character is done, the function returns the last pushed character. If the push back operation is not done properly means if the push back of a character is unsuccessful (e.g. if the file is not open) then EOF character is returned as an error. One can not push back the EOF character to the stream using ungetc. A successful call to ungetc function clears the EOF indicator for the stream.
To erase the push back characters came from call to ungetc function, a call to fseek, fsetpos or fflush functions is made before the character is read from the stream. As all the characters are pushed back are read in, the file position indicator is same as before pushing back the characters.
Ungetc, a restricted version of ungetch
As stated already it is a restricted version of function ungetch, it has same restrictions like when a read operation is immediately folllowed by a write operation or vice versa. That is why, there is a requirement of a intervening reposition between ungetc and the subsequent write or read function.