Example (ungetwc -- Push Wide Character onto Input Stream)

This example reads in wide characters from stream, and then calls ungetwc to push the characters back to the stream.

#include <wchar.h>
#include <wctype.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
   FILE         *stream;
   wint_t       wc;
   wint_t       wc2;
   unsigned int result = 0;
   if (NULL == (stream = fopen("ungetwc.dat", "r+"))) {
      printf("Unable to open file.\n");
      exit(EXIT_FAILURE);
   }
   while (WEOF != (wc = fgetwc(stream)) && iswdigit(wc))
      result = result * 10 + wc - L'0';
   if (WEOF != wc)
      ungetwc(wc, stream);    /* Push the nondigit wide character back */
   /* get the pushed back character */
   if (WEOF != (wc2 = fgetwc(stream))) {
      if (wc != wc2) {
         printf("Subsequent fgetwc does not get the pushed back character.\n");
         exit(EXIT_FAILURE);
      }
      printf("The digits read are '%i'\n"
             "The character being pushed back is '%lc'", result, wc2);
   }
   return 0;
   /****************************************************************************
      Assuming the file ungetwc.dat contains:
      12345ABCDE67890XYZ
      The output should be similar to :
      The digits read are '12345'
      The character being pushed back is 'A'
   ****************************************************************************/
}