Standard Library Functions in C

adplus-dvertising
ungetc() Function
Previous Home Next

Description

The C library function, The ungetc() function pushes the character char back onto stream and clears the end-of-file indicator. The stream must be open for reading. A subsequent read operation on stream starts with char. An attempt to push EOF onto the stream using ungetc is ignored.

Declaration

Following is the declaration for ungetc() function.

int ungetc(int char, FILE *stream)

Parameters

char - This is the character to be pushed back in stream. This is passed as integer promotion of character.

stream - The stream to modify.

Return Value

If successful, each of these functions returns the character argument c. If c cannot be pushed back or if no character has been read, the input stream is unchanged and ungetc returns EOF; ungetwc returns WEOF.

Example

#include <stdio.h>
int main(void)
{
    int ch;
 
    /* reads characters from the stdin and show them on stdout */
    /* until encounters '1' */
 
    while ((ch = getchar()) != '1')
        putchar(ch);
 
    /* ungetc() returns '1' previously read back to stdin */
    ungetc(ch, stdin);
 
    /* getchar() attempts to read next character from stdin */
    /* and reads character '1' returned back to the stdin by ungetc() */
    ch = getchar();
 
    /* putchar() displays character */
    putchar(ch);
    puts("");
 
    printf("Thank you!\n");
    return 0;
}

Output

a
a
v
v
c
c
u
u
1
1
Thank you!
Previous Home Next