Trusted answers to developer questions

How to use getc() in C++

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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:

  1. The “demo.txt” file is opened.
  2. The getc function reads the single character from the file in each iteration of the loop.
  3. The returned value from the function is stored in the variable of type int.
  4. In line 15, the putchar function converts the integer to a character and prints the standard output.
  5. 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 reading
FILE* file = fopen("demo.txt", "r");
int val;
// standard C I/O file reading loop
while (val = getc(file)) {
// breaks from the loop if EOF
if (val == EOF)
break;
putchar(val);
cout << endl;
}
// In case of an error ferror indictor is set true
if (ferror(file))
cout << "Error during file reading" << endl;
//In case when EOF is reached, then feof indicator is set true
if (feof(file))
cout << "Successful execution of function" << endl;
return 0;
}

RELATED TAGS

c++

CONTRIBUTOR

Sadia Zubair
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?