How do I read a file into a std::string
, i.e., read the whole file at once?
Text or binary mode should be specified by the caller. The solution should be standard-compliant, portable and efficient. It should not needlessly copy the string's data, and it should avoid reallocations of memory while reading the string.
One way to do this would be to stat the filesize, resize the std::string
and fread()
into the std::string
's const_cast<char*>()
'ed data()
. This requires the std::string
's data to be contiguous which is not required by the standard, but it appears to be the case for all known implementations. What is worse, if the file is read in text mode, the std::string
's size may not equal the file's size.
A fully correct, standard-compliant and portable solutions could be constructed using std::ifstream
's rdbuf()
into a std::ostringstream
and from there into a std::string
. However, this could copy the string data and/or needlessly reallocate memory.
- Are all relevant standard library implementations smart enough to avoid all unnecessary overhead?
- Is there another way to do it?
- Did I miss some hidden Boost function that already provides the desired functionality?
void slurp(std::string& data, bool is_binary)
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…