I would like to load the contents of a text file into a vector<char>
(or into any char input iterator, if that is possible). Currently my code looks like this:
std::vector<char> vec;
std::ifstream file("test.txt");
assert(file.is_open());
while (!(file.eof() || file.fail())) {
char buffer[100];
file.read(buffer, 100);
vec.insert(vec.end(), buffer, buffer + file.gcount());
}
I do not like the manual use of a buffer (Why 100 chars? Why not 200, or 25 or whatever?), or the large number of lines that this took. The code just seems very ugly and non-C++. Is there a more direct way of doing this?
To store a 1-by- n sequence of characters as a character vector, using the char data type, enclose it in single quotes. The text 'Hello, world' is 12 characters long, and chr stores it as a 1-by-12 character vector. If the text includes single quotes, use two single quotes within the definition.
vector is a container, string is a string.
If you want to avoid reading char by char:
if (!file.eof() && !file.fail()) { file.seekg(0, std::ios_base::end); std::streampos fileSize = file.tellg(); vec.resize(fileSize); file.seekg(0, std::ios_base::beg); file.read(&vec[0], fileSize); }
I think it's something like this, but have no environment to test it:
std::copy(std::istream_iterator<char>(file), std::istream_iterator<char>(), std::back_inserter(vec));
Could be you have to play with io manipulators for things like linebreaks/whitespace.
Edit: as noted in comments, could be a performance hit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With