c++ - Function template: read binary file into std::vector -
problem: i'm trying read binary file std::vector
template function: reading vector doesn't work.
the file format have parse has parts fields guaranteed have same size: parts of file contain array of uint16_t
fields, while others array of uint32_t
, or uint64_t
, etc.
the base idea have template function reads std::vector
passed reference.
i tried use std::vector.insert
or std::copy
doesn't work: vector empty (i can guarantee file accessible , can read). checked documentation std::istream_iterator
.
that's trivial mistake, can't see what's wrong in below code.
problem repro code:
#include <iostream> #include <fstream> #include <vector> #include <cstdint> #include <iterator> template<typename t, typename a> void read_vec(std::ifstream& file, std::ifstream::pos_type offset, size_t count, std::vector<t, a>& vec) { file.seekg(offset, std::ios::beg); //file.unsetf(std::ios::skipws); /* test if can read , dump file t* p = new t[count]; file.read(reinterpret_cast<char*>(p), count * sizeof(t)); (unsigned int = 0; < count; ++i){ t elem = p[i]; std::cout << "e: " << std::hex << elem << std::endl; } delete(p); */ /* //method #1 file.seekg(offset, std::ios::beg); vec.resize(count); vec.insert(vec.begin(), std::istream_iterator<t>(file), std::istream_iterator<t>()); */ // method #2 file.seekg(offset, std::ios::beg); vec.reserve(count); std::copy(std::istream_iterator<t>(file), std::istream_iterator<t>(), std::back_inserter(vec)); } void parse_file_header(std::ifstream& f) { std::vector<uint16_t> vec; read_vec(f, 0x40, 8, vec); (const auto& elem : vec) { std::cout << "e: " << std::hex << elem << std::endl; } } void parse_file(std::string file_path) { std::ifstream file(file_path, std::ios::binary); parse_file_header(file); } int main(void){ parse_file("c:\\tmp\\t512_f.dexp"); return 0; }
Comments
Post a Comment