by Dinesh Thakur Category: File Handling

If a character read from an input stream is not appropriate for the current operation, we can push it back to the stream using the ungetc function. A subsequent character read operation (such as fgetc or getc) on that stream will return this character. The prototype of the ungetc function is given below.

int ungetc ( int c, FILE *fp ) ;

This function converts the character specified by argument c to unsigned char before pushing it to stream fp. If the operation is successful, the function returns the character pushed to the stream; otherwise, it returns an EOF.

The ungetc function is useful in input scanning operations. Consider that we wish to read an integer number from a stream one character at a time (using fgetc or getc). Let us also assume that a number is followed by either a whitespace or a non-numeric character.

For example, each line given below contains two integer numbers: 123 and 1234.

      123 2345

      123,2345

Note that we have no information about the number of digits in the number being read. Only when we read a non-numeric character, will we come to know that the digits in the number are over. However, we have already read the non-numeric character that follows the number being read. This character may be a part of subsequent data item. Hence, we push it back to the stream and it will be read by a subsequent read operation on that stream. ยท

The following points may be noted about the ungetc function:

1. C language guarantees the pushback of only one character. If we perform more than one ungetc operation on a stream without an intervening read or file positioning operation on that stream (such as fseek, fsetpos or rewind), the ungetc function may fail.

2. The character pushed to a stream is actually stored in the buffer associated with the stream. This character is discarded by file positioning operations.



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.