What is ungetc() in C?

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.

Declaration

The declaration of ungetc() is shown below:

int ungetc (int c, FILE * stream);

Parameters

  • c: The int promotion of the character that is to be pushed back.
  • stream: The input stream where the character is pushed back.

Return value

The ungetc() function returns the character written to the input stream if the character is written successfully. EOFEnd-of-file is returned if there is an error when writing to the input stream.

Example

main.c
ungetExample.txt
#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 case
printf("%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;
}

Explanation

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

Copyright ©2025 Educative, Inc. All rights reserved