バイナリファイルの読み書き
たまにしかやらないことは本当によく忘れる。 ましてやMFCなんて。。。
というわけで、fstream, CFileの比較
(参考)
ofstreamでバイナリデータを書き込むspphire9.wordpress.com
エンディアン対応はとりあえずやってない。
// fstream--------------------------------------------------- string filename = "xxxxx.bin" //Write { ofstream ofs(filename, ios::binary); if (!ofs.is_open()) { /* ERROR */ } //1byte単位 char c = val; ofs.write(&c, sizeof(c)); //sizeof(c) == 1 //2byte単位 unsigned short us = val; ofs.write(reinterpret_cast<char*>(&us), sizeof(us)); //sizeof(us) == 2 } //Load { ifstream ifs;(filename, ios::binary); if (!ifs.is_open()) { /* ERROR */ } //1byte単位 char c = 0; ifs.read(&c, sizeof(c)); val = (int)c; //2byte単位 unsigned short us = 0; ifs.read(reinterpret_cast<char*>(&us), sizeof(us)); val = (int)us; } //CFile--------------------------------------------------- CString filename = _T("xxxxx.bin"); //Write { CFile cf; if(!cf.Open(filename, CFile::modeCreate | CFile::modeWrite)){ /* ERROR */ } //1byte単位 char c = (char)val; cf.Write(&c, sizeof(c)); //2byte単位 uint16_t us = (uint16_t)val; cf.Write((char*)&us, sizeof(us)); } //Load { CFile cf; if (!cf.Open(in_fileC, CFile::modeRead)) { /* ERROR */ } //1byte単位 char c = 0; cf.Read(&c, 1); val = (int)c; //2byte単位 unsigned short us = 0; cf.Read((char*)&v, 2); val = (int)us; }