ungetc() — Push Character onto Input Stream

Format

#include <stdio.h>
int ungetc(int c, FILE *stream);

Language Level: ANSI

Threadsafe: Yes.

Description

The ungetc() function pushes the unsigned character c back onto the given input stream. However, only one consecutive character is guaranteed to be pushed back onto the input stream if you call ungetc()consecutively. The stream must be open for reading. A subsequent read operation on the stream starts with c. The character c cannot be the EOF character.

Characters placed on the stream by ungetc() will be erased if fseek(), fsetpos(), rewind(), or fflush() is called before the character is read from the stream.

Return Value

The ungetc() function returns the integer argument c converted to an unsigned char, or EOF if c cannot be pushed back.

The value of errno may be set to:

Value
Meaning
ENOTREAD
The file is not open for read operations.
EIOERROR
A non-recoverable I/O error occurred.
EIORECERR
A recoverable I/O error occurred.

The ungetc() function is not supported for files opened with type=record.

Example that uses ungetc()

In this example, the while statement reads decimal digits from an input data stream by using arithmetic statements to compose the numeric values of the numbers as it reads them. When a non-digit character appears before the end of the file, ungetc() replaces it in the input stream so that later input functions can process it.

#include <stdio.h>
#include <ctype.h>
 
int main(void)
{
   FILE *stream;
   int ch;
   unsigned int result = 0;
   while ((ch = getc(stream)) != EOF && isdigit(ch))
      result = result * 10 + ch - '0';
   if (ch != EOF)
      ungetc(ch,stream);
         /* Put the nondigit character back */
   printf("The result is: %d\n", result);
   if ((ch = getc(stream)) != EOF)
      printf("The character is: %c\n", ch);
}

Related Information



[ Top of Page | Previous Page | Next Page | Contents | Index ]