C Library Function - ungetc()
C Standard Library - <stdio.h>
Description
The C library function int ungetc(int char, FILE *stream) pushes the character char (an unsigned character) back into the specified stream stream so that it is the next character read.
Declaration
Here is the declaration for the ungetc() function.
int ungetc(int char, FILE *stream)
Parameters
char -- This is the character to be pushed back. The character is passed as its corresponding int value.
stream -- This is a pointer to a FILE object that identifies the input stream.
Return Value
On success, it returns the character pushed back, otherwise it returns EOF and the stream remains unchanged.
Example
The following example demonstrates the use of the ungetc() function.
#include <stdio.h>
int main ()
{
FILE *fp;
int c;
char buffer [256];
fp = fopen("file.txt", "r");
if( fp == NULL )
{
perror("Error opening file");
return(-1);
}
while(!feof(fp))
{
c = getc (fp);
/* Replace ! with + */
if( c == '!' )
{
ungetc ('+', fp);
}
else
{
ungetc(c, fp);
}
fgets(buffer, 255, fp);
fputs(buffer, stdout);
}
return(0);
}
Assuming we have a text file file.txt with the following content, which will be used as input in the example:
this is tutorialpro
!c standard library
!library functions and macros
Compiling and running the above program will produce the following result:
this is tutorialpro
+c standard library
+library functions and macros