Defined in header <stdio.h> | ||||
---|---|---|---|---|
|
Puts the character ch
back to the given file stream.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #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:
1 | abbc |
References
- C11 standard (ISO/IEC 9899:2011):
- 7.21.7.10 The ungetc function (p: 334)
- C99 standard (ISO/IEC 9899:1999):
- 7.19.7.11 The ungetc function (p: 300)
- C89/C90 standard (ISO/IEC 9899:1990):
- 4.9.7.11 The ungetc function
See also
gets a character from a file stream (function) | |
C++ documentation for ungetc |
Please login to continue.