I want to read a binary file containing uint16_t values. What I've done so far is:
std::ifstream is;
std::vector<char> rawfilebuffer; /* should be std::vector<uint16_t> */
is.open("uint16_t_file.raw", std::ios::binary);
is.seekg(0, std::ios::end);
size_t filesize=is.tellg();
is.seekg(0, std::ios::beg);
rawfilebuffer.reserve(filesize);
rawfilebuffer.assign(std::istreambuf_iterator<char>(is),
std::istreambuf_iterator<char>());
Using std::istreambuf_iterator<char>
does not work (error: no matching conversion for functional-style cast from 'std::ifstream'
).
Is it possible to cast istreambuf_iterator to uint16_t
?
With c++11, you can use the data()
member of std::vector
and read all of file (or big chunks, if the file is too big).
Something like
#include <vector>
#include <fstream>
#include <iostream>
using myType = uint16_t;
int main ()
{
std::ifstream is;
std::vector<myType> rawfilebuffer;
is.open("uint16_t_file.raw", std::ios::binary);
is.seekg(0, std::ios::end);
size_t filesize=is.tellg();
is.seekg(0, std::ios::beg);
rawfilebuffer.resize(filesize/sizeof(myType));
is.read((char *)rawfilebuffer.data(), filesize);
for ( auto const & ui : rawfilebuffer )
std::cout << '[' << ui << ']';
std::cout << '\n';
return 0;
}
Attention to the file size. If it's an exact multiple of sizeof(myType)
, well.
Otherwise, you should modify you resize instruction in this way
rawfilebuffer.resize(filesize/sizeof(myType)+(filesize%sizeof(myType)?1U:0U));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With