As the question suggests, how do I load a block of a binary file into a vector at a time using C++? I suppose using ifstream_iterator
to solve the problem, but I am not familiar with it. Can anyone give me some code of copying 200 data from a file into a vector at a time? Note that I am using a .bin
file, so my data must be binary.
Asked
Active
Viewed 295 times
0

Chiang Cliff
- 83
- 7
-
1Welcome to SO! You are somewhat more likely to get an answer to this question if you show us what you have tried so far, and how the data you intend to read into memory looks like. – lubgr Jun 15 '21 at 08:57
1 Answers
1
According to the reference:
When reading characters, std::istream_iterator skips whitespace by default (unless disabled with std::noskipws or equivalent), while std::istreambuf_iterator does not. In addition, std::istreambuf_iterator is more efficient, since it avoids the overhead of constructing and destructing the sentry object once per character.
ifstream_iterator
is not designed to be used to read binary files, we need to use istreambuf_iterator
instead, and open file with std::ios::in | std::ios::binary
flags
A sample code may like this:
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
int main(int argc, char* argv[]) {
std::string fname{"you_file"};
std::ifstream ifs(fname, std::ios::in | std::ios::binary);
std::istreambuf_iterator<char> iter(ifs);
std::vector<char> vec(iter, std::istreambuf_iterator<char>{});
std::cout << "bytes:" << vec.size() << std::endl;
return 0;
}
If you have multiple files to read, then wrap the code snippet into a function and call it with a loop.

prehistoricpenguin
- 6,130
- 3
- 25
- 42