ungetc Function

Pushes character back onto stream.

Include

<stdio.h>

Prototype

int ungetc(int c, FILE *stream);

Arguments

c character to be pushed back
stream pointer to the open stream

Return Value

Returns the pushed character if successful; otherwise, returns EOF.

Remarks

The pushed back character will be returned by a subsequent read on the stream. If more than one character is pushed back, they will be returned in the reverse order of their pushing. A successful call to a file positioning function (fseek, fsetpos or rewind) cancels any pushed back characters. Only one character of push back is guaranteed. Multiple calls to ungetc without an intervening read or file positioning operation may cause a failure.

Example

#include <stdio.h> /* for ungetc, fgetc,     */
                   /* printf, fopen, fclose, */
                   /* FILE, NULL, EOF        */

int main(void)
{
  FILE *buf;
  char y, c;

  if ((buf = fopen("afile.txt", "r")) == NULL)
    printf("Cannot open afile.txt\n");
  else
  {
    y = fgetc(buf);
    while (y != EOF)
    {
      if (y == 'r')
      {
        c = ungetc(y, buf);
        if (c != EOF)
        {
          printf("2");
          y = fgetc(buf);
        }
      }
      printf("%c", y);
      y = fgetc(buf);
    }
    fclose(buf);
  }
}

Example Input

Contents of afile.txt (used as input):

Short
Longer string

Example Output

Sho2rt
Longe2r st2ring