データの保存のために、バイナリフォーマットは広く使われている。なのでそれを読まなければならないケースが多い。
C++におけるバイナリの読み方の一番の基本はstream
の関数std::basic_istream::read(char_type*, streamsize)
だろう。
この関数は第二引数で示された文字数だけ読み込み、第一引数で示された位置へその内容を書き込む。
使い方は以下だ。
std::ifstream ifs("example.bin", std::ios::in | std::ios::binary); std::int32_t i; ifs.read(reinterpret_cast<char*>(std::addressof(i)), sizeof(std::int32_t)/* or simply 4 */);
なので、基本的に以下のような関数を用意することで、ストリームから簡単にバイナリ値を読み込むことができる。
template<typename T> T read_binary_as(std::istream& is) { T val; is.read(reinterpret_cast<char*>(std::addressof(val)), sizeof(T)); return val; } const auto i = read_binary_as<std::int32_t>(ifs);
書き出しの時は同様にbasic_ostream::write(const char_type*, streamsize);
が使える。
std::ofstream ofs("example.bin", std::ios::out | std::ios::binary); const std::int32_t i = 42; ofs.write(reinterpret_cast<const char*>(std::addressof(i)), sizeof(std::int32_t))
ラッパーを書くとすれば
template<typename T> std::ostream& write_as_binary(std::ostream& os, const T& v) { is.write(reinterpret_cast<const char*>(std::addressof(val)), sizeof(T)); return val; }
という感じだろうか。
続きを読む