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>
The function takes in one parameter: a pointer to a file object that recognizes an input stream.
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
.
The code below explains how the getc
function works:
getc
function reads the single character from the file in each iteration of the loop.int
.putchar
function converts the integer to a character and prints the standard output.#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