C++ program to read a text file

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.

Logic

  1. Open file in read/input mode using std::in
  2. Check file exists or not, if it does not exist terminate the program
  3. If file exist, run a loop until EOF (end of file) not found
  4. Read a single character using cin in a temporary variable
  5. And print it on the output screen
  6. Close the file

Program to read text character by character in C++

#include<iostream>
#include<fstream>
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.





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.