Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a binary file into a std::vector<uint16_t> instead of std::vector<char>

Tags:

c++

c++11

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?

like image 870
Johann Horvat Avatar asked Apr 15 '16 10:04

Johann Horvat


1 Answers

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));
like image 133
max66 Avatar answered Sep 27 '22 17:09

max66