C Standard Library

C <wchar.h> - ungetwc() Function



The C <wchar.h> ungetwc() function pushes the wide character wc back onto the given input stream, decreasing its internal file position as if a previous getwc() 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 ungetwc() 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 ungetwc() were performed, read operations retrieve the pushed-back characters in reverse order of ungetwc().

If the argument passed for the character parameter is WEOF, 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 ungetwc() have been read or discarded.

Note: This function is wide character equivalent of ungetc() function.

Syntax

wint_t ungetwc (wint_t wc, FILE * stream);

Parameters

wc Specify a wide 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 wide character put back is returned.
  • On failure, WEOF 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 <stdio.h>
#include <wchar.h>

int main(){
  wint_t wc;
  wchar_t buffer [256];

  //open the file in read mode
  FILE *pFile = fopen("test.txt", "r");
  
  //replacing . with !
  while ((wc = getwc(pFile)) != WEOF) {  
    if (wc == L'.') ungetwc (L'!', pFile);
    else ungetwc (wc, pFile);
      
    wc = getwc(pFile);
    putchar (wc); 
  }

  //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 <wchar.h> Library