まずバイナリファイルの読み書きを行う簡単なサンプルを見てみる。
#include <iostream> #include <fstream> #include <cmath> using std::cout; using std::cin; using std::endl; using std::ios; using std::fstream; int main() { // これをoutfile.datにバイナリ書き込みする char n = 99; double nd = std::acos(-1); // バイナリ出力モードで開く fstream ofile("./outfile.dat", ios::binary | ios::out); // 宣言と初期化別々に //fstream ofile; //ofile.open("./outfile.dat", ios::binary | ios::out); // 読み込みはこっち //ofile.open("./outfile.dat", ios::binary | ios::in); // 書き込む時は、データのある領域の先頭アドレスと、 //そこから何バイト書き込むかを引数で渡す //基本的にconst charで書き込むので、それ以外の場合はキャストする。 //キャストには reinterprit_cast<>を使う cout << "ファイルに" << n << "をバイナリで" << sizeof(n) << " byte書き込みます" << endl; ofile.write(reinterpret_cast<char*>(&n), sizeof(n)); cout << "ファイルに" << nd << "をバイナリで" << sizeof(nd) << " byte書き込みます" << endl; ofile.write(reinterpret_cast<char*>(&nd), sizeof(nd)); // 読み込む //ofile.read(reinterpret_cast<char*>(&n), sizeof(n)); //ofile.read(reinterpret_cast<char*>(&nd), sizeof(nd)); // 閉じる ofile.close(); }