C++ Standard Library C++ STL Library

C++ <cstdio> - ungetc() Function



The C++ <cstdio> ungetc() function pushes the character ch (reinterpreted as unsigned char) back onto the given input stream, decreasing its internal file position as if a previous getc() operation was undone. A subsequent read operation on the stream starts with that character. The external device associated with the stream is not modified.

Stream repositioning operations fseek(), fsetpos(), and rewind() discard any characters previously put back into it with this function.

If ungetc() is called more than once without an intervening read or repositioning, it may fail (in other words, a pushback buffer of size 1 is guaranteed, but any larger buffer is implementation-defined). If multiple successful ungetc() were performed, read operations retrieve the pushed-back characters in reverse order of ungetc().

If the argument passed for the character parameter is EOF, the operation fails and the input stream remains unchanged.

If successful, the function clears the end-of-file indicator of stream (if it was currently set), and decrements its internal file position indicator if it operates in binary mode. In text mode, the position indicator has unspecified value until all characters put back with ungetc() have been read or discarded.

Syntax

int ungetc( int ch, FILE * stream );

Parameters

ch Specify a character to be pushed into the input stream buffer.
stream Specify a pointer to a FILE object that specifies an input stream.

Return Value

  • On success, the character put back is returned.
  • On failure, EOF is returned and the given stream remains unchanged.

Example:

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, this file is opened in read mode for reading and printing its content. It first gets each character and puts it back into the stream replacing any "." character found by "!" character.

#include <cstdio>
 
int main(){
  int ch;
  char buffer [256];

  //open the file in read mode
  FILE *pFile = fopen("test.txt", "r");
  
  //replacing . with !
  while ((ch = getc(pFile)) != EOF) {  
    if (ch == '.') ungetc ('!', pFile);
    else ungetc (ch, pFile);
      
    ch = getc(pFile);
    putchar (ch); 
  }

  //close the file
  fclose(pFile);

  return 0;
}

The output of the above code will be:

This is a test file!
It contains dummy content!

❮ C++ <cstdio> Library