×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object 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

  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 <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.

Comments and Discussions!

Load comments ↻





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