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 b
I do not have enough reputation to comment directly on responses using tellg()
.
Please be aware that tellg()
can return -1 on error. If you're passing the result of tellg()
as an allocation parameter, you should sanity check the result first.
An example of the problem:
...
std::streamsize size = file.tellg();
std::vector buffer(size);
...
In the above example, if tellg()
encounters an error it will return -1. Implicit casting between signed (ie the result of tellg()
) and unsigned (ie the arg to the vector
constructor) will result in a your vector erroneously allocating a very large number of bytes. (Probably 4294967295 bytes, or 4GB.)
Modifying paxos1977's answer to account for the above:
string readFile2(const string &fileName)
{
ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);
ifstream::pos_type fileSize = ifs.tellg();
if (fileSize < 0) <--- ADDED
return std::string(); <--- ADDED
ifs.seekg(0, ios::beg);
vector bytes(fileSize);
ifs.read(&bytes[0], fileSize);
return string(&bytes[0], fileSize);
}