The ungetc()
function pushes back a character to an input stream. As the name suggests, the ungetc()
function places the character back to the input stream and decrements its file pointer by one location, as if the getc()
operation never happened.
Note:
ungetc()
is not an output function; it is an input function.
The declaration of ungetc()
is shown below:
int ungetc (int c, FILE * stream);
c
: The int promotion of the character that is to be pushed back.stream
: The input stream where the character is pushed back.The ungetc()
function returns the character written to the input stream if the character is written successfully.
#include<stdio.h>int main() {FILE * fptr= fopen("ungetExample.txt", "r+");if(fptr==NULL){printf("Could not open file!! \n");}while (!feof(fptr)){int c = getc(fptr);if(c!=EOF){if(c=='W' || c=='H'){int c2 = ungetc(c+32, fptr);//to lower caseprintf("%c",c2);}else{int c2 = ungetc(c, fptr);printf("%c",c2);}c = getc(fptr);//incrementing file pointer by one character as it will be decremented by ungetc()}}return 0;}
The code snippet above reads a file character by character, and if a character is in uppercase, it converts the character to lowercase by adding 32 in its ASCII value. The characters are then written back to the file using the ungetc()
function.
Free Resources