mercredi 13 janvier 2021

How to avoid calling memcpy() when appending to vector

The code below reads a binary file in 1024-byte chunks (blocks), saves them into vector<array<char,1024>> and, finally, prints first byte of each block:

#include <iostream>
#include <fstream>
#include <vector>
#include <array>
#include <iomanip>
#include "string.h"

using namespace std;

int main()
{
   vector<array<char,1024>> blocks;
   vector<char> buffer(1024,0);

   ifstream input("./video.mp4", std::ifstream::binary);

   while( !input.eof() ) {
      input.read( buffer.data(), buffer.size() );
      auto size = input.gcount();

      array<char,1024> aa;
      memcpy( aa.data(), buffer.data(), size );

      blocks.push_back( aa );
   }

   for( auto b: blocks ) {
      cout<<hex<<setw(2)<<setfill('0')<<(int)(uint8_t)b[0]<<'\n';
   }
}

I would like to avoid calling memcpy, since this is arguably not comme il faut. How can I accomplish the above functionality using only C++ std library? I believe my compiler supports up to C11 only.

Aucun commentaire:

Enregistrer un commentaire