VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-read-file-into-string-in-cpp/

⇱ How to Read File into String in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Read File into String in C++?

Last Updated : 23 Jul, 2025

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


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)

Comment