What is the best way to read an entire file into a std::string in C++? -
how read file std::string
, i.e., read whole file @ once?
text or binary mode should specified caller. solution should standard-compliant, portable , efficient. should not needlessly copy string's data, , should avoid reallocations of memory while reading string.
one way stat filesize, resize std::string
, fread()
std::string
's const_cast<char*>()
'ed data()
. requires std::string
's data contiguous not required standard, appears case known implementations. worse, if file read in text mode, std::string
's size may not equal file's size.
a correct, standard-compliant , portable solutions constructed using std::ifstream
's rdbuf()
std::ostringstream
, there std::string
. however, copy string data and/or needlessly reallocate memory. relevant standard library implementations smart enough avoid unnecessary overhead? there way it? did miss hidden boost function provides desired functionality?
please show suggestion how implement it.
void slurp(std::string& data, bool is_binary)
taking account discussion above.
and fastest (that know of, discounting memory-mapped files):
string str(static_cast<stringstream const&>(stringstream() << in.rdbuf()).str());
this requires additional header <sstream>
string stream. (the static_cast
necessary since operator <<
returns plain old ostream&
know in reality it’s stringstream&
cast safe.)
split multiple lines, moving temporary variable, more readable code:
string slurp(ifstream& in) { stringstream sstr; sstr << in.rdbuf(); return sstr.str(); }
or, once again in single line:
string slurp(ifstream& in) { return static_cast<stringstream const&>(stringstream() << in.rdbuf()).str(); }
Comments
Post a Comment