Home »
C++ programs »
C++ file handling programs
C++ program to read a text file
Problem statement
In this program, we will learn how to open and read text from a text file character by character in C++?
Here, we have a file named "test.txt", this file contains following text:
Hello friends, How are you?
I hope you are fine and learning well.
Thanks.
We will read text from the file character by character and display it on the output screen.
Steps to read a text file
- Open file in read/input mode using std::in
- Check file exists or not, if it does not exist terminate the program
- If file exist, run a loop until EOF (end of file) not found
- Read a single character using cin in a temporary variable
- And print it on the output screen
- Close the file
Program to read text character by character in C++
#include <fstream>
#include <iostream>
using namespace std;
int main() {
char ch;
const char *fileName = "test.txt";
// declare object
ifstream file;
// open file
file.open(fileName, ios::in);
if (!file) {
cout << "Error in opening file!!!" << endl;
return -1; // return from main
}
// read and print file content
while (!file.eof()) {
file >> noskipws >> ch; // reading from file
cout << ch; // printing
}
// close the file
file.close();
return 0;
}
Output
Hello friends, How are you?
I hope you are fine and learning well.
Thanks.