How to use getc() in C++
The getc function is a C library function that reads the single character value from an input stream.
In order to use the getc function, the stdio header file needs to be included in the program, as shown below:
#include <stdio.h>
Parameters
The function takes in one parameter: a pointer to a file object that recognizes an input stream.
Return Value
Upon successful execution of the function, it returns the integer value, i.e., the ASCII value of the read character. In case of errors, End-of-File (EOF) is returned. If the EOF condition causes the failure, it sets the EOF indicator feof on stream; else, it sets the error indicator to ferror.
Example
The code below explains how the getc function works:
- The “demo.txt” file is opened.
- The
getcfunction reads the single character from the file in each iteration of the loop. - The returned value from the function is stored in the variable of type
int. - In line 15, the
putcharfunction converts the integer to a character and prints the standard output. - After the standard file reading loop, error handling takes over.
main.cpp
demo.txt
#include <iostream>#include <stdlib.h>using namespace std;int main() {//file readingFILE* file = fopen("demo.txt", "r");int val;// standard C I/O file reading loopwhile (val = getc(file)) {// breaks from the loop if EOFif (val == EOF)break;putchar(val);cout << endl;}// In case of an error ferror indictor is set trueif (ferror(file))cout << "Error during file reading" << endl;//In case when EOF is reached, then feof indicator is set trueif (feof(file))cout << "Successful execution of function" << endl;return 0;}
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved