Namespaces
Variants
Views
Actions

ungetc

From cppreference.com
< c‎ | io
Revision as of 06:45, 1 May 2014 by Newatthis (Talk | contribs)

 
 
File input/output


Functions
File access
Direct input/output
Unformatted input/output
(until C11)(since C11)
ungetc
(C95)(C95)
(C95)
(C95)(C95)
(C95)
(C95)
Formatted input
Formatted output
File positioning
Error handling
Operations on files
 
Defined in header <stdio.h>
int ungetc( int ch, FILE *stream );

Puts the character ch back to the given file stream.

Contents

Parameters

ch - character to be put back
stream - file stream to put the character back to

Return value

On success ch is returned.

On failure EOF is returned and the given stream remains unchanged.

Example

ungetc with error checking

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    FILE* fp = fopen("test.txt", "w");
    fputs("abc\n", fp);
    fclose(fp);
    fp = fopen("test.txt", "r");
 
    /* Read  "abc".  */
    /* Write "abbc". */
    char ch;
    int ret_code;
    ch=fgetc(fp);   /* read 'a' */
    putchar(ch);
    ch=fgetc(fp);   /* read 'b' */
    putchar(ch);
 
    ret_code = ungetc(ch,fp);   /* push 'b' back to input file */
    /* Test whether EOF was reached. */
    if (ret_code == EOF)
       if (ferror(fp)) 
       {
          perror("ungetc()");
          fprintf(stderr,"ungetc() failed in file %s at line # %d\n", __FILE__,__LINE__-6);
          exit(EXIT_FAILURE);
       }
 
    ch=fgetc(fp);   /* reread 'b' */
    putchar(ch);
    ch=fgetc(fp);   /* read 'c'   */
    putchar(ch);
 
    return EXIT_SUCCESS;
}

Output:

abbc

See also

gets a character from a file stream
(function) [edit]