cplusplus
cplusplus

 

Introduction

In C++, file handling is an essential feature for interacting with files stored on the computer. One of the most common operations is reading the contents of a file and displaying them on the screen. The ability to read files allows programmers to manipulate data stored in external files, process it, and display it in various forms. In this example, we will create a simple program that reads the contents of a file and displays it on the console.

Objective

The objective of this program is to demonstrate how to use C++ file handling to read a file and display its contents on the console. This will include:

  • Opening a file using the C++ file I/O stream.
  • Reading from the file and storing its content.
  • Displaying the content on the console.

Code

#include <iostream>
#include <fstream>   // Required for file handling
#include <string>

using namespace std;

int main() {
    string filename = "example.txt";  // File to be read
    ifstream file(filename);          // Open file for reading

    // Check if the file is opened successfully
    if (!file) {
        cerr << "Error: Could not open the file!" << endl;
        return 1;  // Exit with error code if file cannot be opened
    }

    string line;
    cout << "File contents:\n";
    
    // Read the file line by line and display each line
    while (getline(file, line)) {
        cout << line << endl;
    }

    file.close();  // Close the file after reading

    return 0;
}

Explanation of the Program

The program follows a simple flow:

  1. File Opening: The file is opened using an ifstream object. The file’s name is given as “example.txt”, but you can modify this to any file path you want to read. The ifstream constructor attempts to open the file for reading.
  2. File Check: A check is performed using if (!file) to ensure that the file opened successfully. If the file cannot be opened, an error message is displayed using cerr and the program exits with a return code of 1.
  3. Reading and Displaying: The program reads the file line by line using getline(file, line). Each line of the file is then displayed on the console using cout.
  4. Closing the File: After reading the entire content, the file is closed using file.close().

How to Run the Program

To run the program, follow these steps:

  1. Create the Source Code: Open a text editor or IDE of your choice, such as Visual Studio Code, Code::Blocks, or any C++ editor. Paste the code into a new file and save it with a .cpp extension (e.g., read_file.cpp).
  2. Prepare the Input File: Ensure that you have a text file named example.txt in the same directory as the program, or modify the program to point to a specific file path.
  3. Compile the Program: Open a terminal or command prompt. Navigate to the directory containing the program and run the C++ compiler to compile the program. For example, use the following command with g++:
    g++ read_file.cpp -o read_file
  4. Run the Executable: Once compiled, run the program with the following command:
    ./read_file
  5. View Output: The program will display the contents of the example.txt file on the terminal or console.
© 2024 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)