The function ungetc () in C
The function int ungetc (int char, FILE * stream) in the C Library standard pushes the char character (an unsigned char) onto the Stream given to the next character to be read.
The function int ungetc (int char, FILE * stream) in the C Library standard pushes the char character (an unsigned char) onto the Stream given to the next character to be read.
Declare the ungetc () function in C
Below is the declaration for the ungetc () function in C:
int ungetc ( int char , FILE * stream )
Parameters
char - This is a character to be pushed back.
stream - This is the pointer to a FILE object that identifies the Input Stream.
Returns the value
If successful, it returns the character that was pushed back. Otherwise, the function returns EOF and Stream remains unchanged.
For example
The following program C illustrates the usage of the ungetc () function in C:
#include int main () { FILE * fp ; int c ; char buffer [ 256 ]; fp = fopen ( "baitapc.txt" , "r" ); if ( fp == NULL ) { perror ( "Xuat hien loi trong khi mo baitapc.txt" ); return (- 1 ); } while (! feof ( fp )) { c = getc ( fp ); /* thay the ky tu ! boi ky tu + */ if ( c == '!' ) { ungetc ( '+' , fp ); } else { ungetc ( c , fp ); } fgets ( buffer , 255 , fp ); fputs ( buffer , stdout ); } return ( 0 ); }
Suppose we have the bait.txt file that contains the following data. This file will be used as input.
Compile and run the above C program to see the results.
According to Tutorialspoint
Previous lesson: Ham puts () in C
Next lesson: Function of perror () in C
You should read it
Maybe you are interested
Discovered mysterious signals emanating from a star right next to the Solar System, possibly of aliens NASA reveals its latest snapshot of the Martian surface with a resolution of 1.8 billion pixels Found the second planet of Proxima Centauri, the star closest to the sun 7 most modern astronaut ships on the planet Is Proxima b our 'neighbor' planet? Why have scientists found Proxima b - '2nd Earth' until now?