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

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile