lundi 7 mai 2018

What is the C++11 way of reading binary files (16-bits at a time)?

I want to read a binary file in 16 bit words. Right now, I'm using an std::ifstream to read into a 2 character array c.

#include <iostream>
#include <fstream>
#include <stdint.h>

int main() {
  std::ifstream file("./tetris.rom", std::ios::in | std::ios::binary);
  char c[2];
  while (file.read(c, 2)) {
    uint16_t word1 = (static_cast<uint8_t>(c[0]) << 8) | static_cast<uint8_t>(c[1]);
    std::cout << "word\t" << std::hex << word << std::endl;
  }
}

This works for me, but is there a better (either safer or faster) way of doing this in C++11?

Aucun commentaire:

Enregistrer un commentaire