Read a file into a string
#include <fstream> #include <streambuf> #include <string> #include <algorithm> #include <iterator> #include <cerrno> std::string get_file_contents(const char *filename) { std::ifstream in(filename, std::ios::in | std::ios::binary); if (in) { std::string contents; in.seekg(0, std::ios::end); contents.reserve(in.tellg()); in.seekg(0, std::ios::beg); std::copy((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>(), std::back_inserter(contents)); in.close(); return(contents); } throw(errno); }
This has been benchmarked in a blog1, and compared to other methods is the fastest:
Method Duration ================ C/C++ 24.5 Rdbuf 32.5 Copy 62.5 Iterator 64.5 Assign 68
Although you can probably achieve faster speeds by using POSIX, as stated in a comment.