convert a file to a std::string

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

int main()
{
/*
I wanna to convert a text file to a std::string quickly;
The following method is what I find out.
Who can imporve it, more efficiently?
*/
std::ifstream fin(R"(C:\Users\WZH\Desktop\1.txt)");
std::stringstream ss;
ss << fin.rdbuf();
std::string result = ss.str();


std::cin.get();
return 0;
}
1
2
3
4
5
6
7
std::string file_to_string( const std::string& path_to_file )
{
    std::ifstream file(path_to_file) ;

    // http://en.cppreference.com/w/cpp/iterator/istreambuf_iterator
    return { std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>() } ;
}

http://coliru.stacked-crooked.com/a/631d29b7d5887821
Last edited on
You might find the file length, allocate a std::string of that size, and use read() to directly read into the string's data area.

Example code here does something similar, but doesn't use std::string.
http://www.cplusplus.com/reference/istream/istream/seekg/
Last edited on
Topic archived. No new replies allowed.