What is the best way to read an entire file into a std::string in C++?



To read an entire file into a std::string in C++, you can open the file using std::ifstream, read its contents using a std::stringstream or by moving the file pointer at the specified position, and then store the result in a std::string.

Algorithm

Here is a simple algorithm to read an entire file into a std::string in C++:

Begin.
   Open the file using an ifstream object.
   Check if the file is successfully opened.
   Create an ostringstream object.
   Read the file content using rdbuf() and write it into the ostringstream.
   Convert the ostringstream to a std::string.
   Print the string content.
End.

C++ Program to Read an Entire File into a std::string

This program reads the entire content of the file(x.txt) into a std::string using a string stream and prints the output as "hi". If the file can't be opened, it shows an error message:

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
int main() {
   // Open the file
   std::ifstream f("a.txt"); 
   std::string str;
   if (f) {
      std::ostringstream ss;
   // Read entire file into stringstream
      ss<<f.rdbuf();
   // Convert to string
      str = ss.str();
   } else {
      std::cerr<<"Error: Could not open the file.\n";
      return 1;
   }
   // Print file content
   std::cout<<str<<'\n';  
   return 0;
}

If the file opens, the output will be:

hi

If the file can't open, the output will be:

Error: Could not open the file.
Revathi Satya Kondra
Revathi Satya Kondra

Technical Content Writer, Tutorialspoint

Updated on: 2025-06-10T15:02:33+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements