In this section, we will learn what the ungetc() function is and how it works in C.
C ungetc() Function: Unread
Sometimes when we’re reading the content of a file like a text, we might realize the character that has been read is something that shouldn’t be read! So, via the call to the `ungetc()` function, we can put back that character to the incoming stream as if the character wasn’t read at all! So the next time we call to read a character from the same file, we will get the same character.
Note: the prototype of the function is in `stdio.h` header file and so make sure the file is included in the program.
C ungetc() Function Syntax:
Here’s the prototype of the function:
int ungetc(int char, FILE *stream)
C ungetc() Function Parameters
The function takes 2 arguments:
- The first argument is the character that we want to push to the incoming stream.
- The second argument is the address of the memory space allocated to the FILE-structure of the target file.
C ungetc() Function Return Value
The returned value of the function is the same character that is set as the first argument of the function if the operation was successful and EOF otherwise.
Example: using ungetc() function in C
#include <stdio.h> #include <stdlib.h> int main() { FILE *file = fopen("G:/fileOne.txt","r"); if (file == NULL){ printf("Could not open the file"); exit(EXIT_FAILURE); } char c; int i = 0; while ((c= getc(file)) !=EOF){ printf("%c",c); ungetc(c, file); if (i == 10){ break; } i++; } fclose(file); printf("\nDone\n"); return 0; }
Output:
HHHHHHHHHHH Done
How Does ungetc() Function Work in C?
In this example we pushed back the first character got from the incoming stream via the call to the `ungetc()` function and as you can see for every call to read the next character of the file, we’ve got the same character again.