C Library Function - ungetc()
Description
C library function *int ungetc(int char, FILE stream) Pushes the character char(an unsigned char) back into the specified stream stream so that it is the next character to be read.
Declaration
Below is the declaration of 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
If successful, the pushed-back character is returned; otherwise EOF is returned and the stream remains unchanged.
Example
The following example demonstrates the use of the ungetc() function.
Example
#include
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
)
;
}
Suppose we have a text file file.txt, whose content is as follows. The file will be used as input in the example:
this is runoob
!c standard library
!library functions and macros
Let's compile and run the above program, which will produce the following result:
this is runoob
+c standard library
+library functions and macros
C Standard Library -