I would like to load the contents of a text file into a vector
(or into any char input iterator, if that is possible). Currently my code looks like
There were lots of good responses. Thanks all! The code that I have decided on using is this:
std::vector vec;
std::ifstream file;
file.exceptions(
std::ifstream::badbit
| std::ifstream::failbit
| std::ifstream::eofbit);
//Need to use binary mode; otherwise CRLF line endings count as 2 for
//`length` calculation but only 1 for `file.read` (on some platforms),
//and we get undefined behaviour when trying to read `length` characters.
file.open("test.txt", std::ifstream::in | std::ifstream::binary);
file.seekg(0, std::ios::end);
std::streampos length(file.tellg());
if (length) {
file.seekg(0, std::ios::beg);
vec.resize(static_cast(length));
file.read(&vec.front(), static_cast(length));
}
Obviously, this is not suitable for extremely large files or performance-critical code, but it is good enough for general purpose use.