Sunday, July 20, 2014

Read a binary file (or part of it) into a std::vector in c++

You can do this with c arrays, of course, but std::vector has many more features and is much more convenient. Here is a demo:


 std::vector<unsigned char> buffer;
 buffer.reserve(bytes_read);
 std::vector<unsigned char> snp_buffer(bytes_snp);

 for(uintvec::iterator offset_i = snp_skip_start; offset_i != snp_skip_end; offset_i++) {
  fseeko(file_in, *offset_i, SEEK_SET);
  size_t fread_ret = fread(&snp_buffer.front(), bytes_snp, 1, file_in);
  if(! fread_ret) {
   throw "Failed to read into buffer!";
  }
  buffer.insert(buffer.end(), snp_buffer.begin(), snp_buffer.end());
 }

0 comments: