1

Very often it is necessary to read a whole file content into an std::string. Which is the easiest way of doing that?

Fernando
  • 1,287
  • 1
  • 10
  • 28
  • 2
    Possible duplicate of [Read whole ASCII file into C++ std::string](http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring). See also: [Read file-contents into a string in C++](http://stackoverflow.com/questions/2912520/read-file-contents-into-a-string-in-c) or [What is the best way to slurp a file into a std::string in c++?](http://stackoverflow.com/questions/116038/what-is-the-best-way-to-slurp-a-file-into-a-stdstring-in-c) – Vincent Savard Apr 26 '16 at 17:05

1 Answers1

3

Let's assume that we have a file "test.txt". Generally, the best way I find of doing that is using the following code:

#include <iostream>
#include <sstream>
#include <fstream>

int main()
{
    std::ifstream ifs("test.txt");
    std::stringstream buffer;
    buffer << ifs.rdbuf();

    std::cout << buffer.str() << std::endl;

    return 0;
}
Fernando
  • 1,287
  • 1
  • 10
  • 28
  • A recommendation: rather than coding the read into `main`, putting the reading code into a `std::string readfiletostring(const std::string & filename)` or similar function generalizes the solution. Then you you can demonstrate its use with a `main` that consists of `std::cout << readfiletostring("test.txt") << std::endl;` if required. – user4581301 Apr 26 '16 at 17:46