How to Read File into String in C++?

In C++, file handling allows us to read and write data to an external file from our program. In this article, we will learn how to read a file into a string in C++.

Reading Whole File into a C++ String

To read an entire file line by line and save it into std::string, we can use std::ifstream class to create an input file stream for reading from the specified file with a combination of std::getline to extract the lines from the file content that can be concatenated and stored in a string variable.

Approach

  • Open the file using std::ifstream file(filePath).
  • Use the is_open() method to check if the file was opened successfully, if not print error message and return.
  • Use a loop with std::getline(file, line) to read each line of the file into a string and print the populated string.
  • Close the file stream.

C++ Program to Read a File into String

The below program demonstrates how we can read the content of a file into a std::string line by line in C++.

C++
// C++ Program to demonstrate how to Read a File into String
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{

    // get the filepath
    string filePath = "myFile.txt";

    // Open the file using ifstream
    ifstream file(filePath);

    // confirm file opening
    if (!file.is_open()) {
        // print error message and return
        cerr << "Failed to open file: " << filePath << endl;

        return 1;
    }

    // Read the file line by line into a string
    string line;
    while (getline(file, line)) {
        cout << line << endl;
    }

    // Close the file
    file.close();

    return 0;
}


Output

File Content: 
Hi, Geek!
Welcome to gfg.
Happy Coding ;)

Time Complexity: O(n), here n is total number of characters in the file.
Auxiliary Space: O(n)

 

 


Contact Us