
- The C Standard Library
- C Library - Home
- C Library - <assert.h>
- C Library - <ctype.h>
- C Library - <errno.h>
- C Library - <float.h>
- C Library - <limits.h>
- C Library - <locale.h>
- C Library - <math.h>
- C Library - <setjmp.h>
- C Library - <signal.h>
- C Library - <stdarg.h>
- C Library - <stddef.h>
- C Library - <stdio.h>
- C Library - <stdlib.h>
- C Library - <string.h>
- C Library - <time.h>
- C Standard Library Resources
- C Library - Quick Guide
- C Library - Useful Resources
- C Library - Discussion
- C Programming Resources
- C Programming - Tutorial
- C - Useful Resources
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C library function - ungetc()
Description
The C library function int ungetc(int char, FILE *stream) pushes the character char (an unsigned char) onto the specified stream so that the this is available for the next read operation.
Declaration
Following is the declaration for ungetc() function.
int ungetc(int char, FILE *stream)
Parameters
char − This is the character to be put back. This is passed as its int promotion.
stream − This is the pointer to a FILE object that identifies an input stream.
Return Value
If successful, it returns the character that was pushed back otherwise, EOF is returned and the stream remains unchanged.
Example
The following example shows the usage of ungetc() function.
#include <stdio.h> int main () { FILE *fp; int c; char buffer [256]; fp = fopen("file.txt", "r"); if( fp == NULL ) { perror("Error in 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); }
Let us assume, we have a text file file.txt, which contains the following data. This file will be used as an input for our example program −
this is tutorials point !c standard library !library functions and macros
Now, let us compile and run the above program that will produce the following result −
this is tutorials point +c standard library +library functions and macros