How would I do this using STL algorithms?
std::ifstream file(filename);
std::vector<unsigned char> buf;
for(auto file_it = std::istreambuf_iterator<char>(file); file_it != std::istreambuf_iterator<char>() && buf.size() < 2048; ++file_it)
buf.push_back(*file_it);
Note buf.size() < 2048.
e.g. what will happen if I do the following, and the file is smaller than 2048 bytes?
std::copy_n(std::istreambuf_iterator<char>(file), 2048, std::back_inserter(buf));
Like the documentation says,
std::copy_n()will copy exactlynitems. It will keep reading past the end of the sequence the iterator refers to. I’m not sure what the standard says aboutistreambuf_iterator<>, though. It’s probably undefined behavior, but streams are likely to produce lots of copies ofeof()past the end. This might lead to lots of garbage when there are less than2048bytes available.In any case, if you want to reliably copy up to
nitems, you’ll need to write your own function:Some people might use
std::iterator_traits<>instead of an extra template parameter to force the same distance type as the iterator.