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've just finished reading the article "The function ungetc () in C" edited by the TipsMake team. You can save the-function-ungetc-in-c.pdf to your computer here to read later or print it out. We hope this article has provided you with many useful tech tips and tricks. You can search for similar articles on tips and guides. Thank you for reading and for following us regularly.

« PREV : The function perror...
Function puts () in... : NEXT »