Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a file into a vector<char>

Tags:

c++

iostream

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?

like image 651
Mankarse Avatar asked Aug 30 '11 10:08

Mankarse


People also ask

How do I save a character in a vector?

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.

Is vector char a string?

vector is a container, string is a string.


2 Answers

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); } 
like image 95
hamstergene Avatar answered Sep 25 '22 17:09

hamstergene


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.

like image 20
KillianDS Avatar answered Sep 25 '22 17:09

KillianDS