はじめに
C++でバイナリの入出力する方法を紹介します。
現在の案件で久しぶりにC++を使用していて、全然覚えていないので自分用メモです。
ソースコード
例として構造体をバイナリファイルに書込み、読込みを行っています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
#include <stdio.h> #include <iostream> #include <fstream> namespace { const char* FileName = "test.bin"; }; struct BinaryData { int Value; char Text[10]; }; int main() { BinaryData data = { 999, "abcdefghi" }; // バイナリでファイル書込み std::ofstream ofs(FileName, std::ios::out | std::ios::trunc | std::ios::binary); if (ofs.is_open()) { ofs.write(reinterpret_cast<char*>(&data.Value), sizeof(int)); ofs.write(data.Text, sizeof(char) * 10); ofs.close(); } data = { 0 }; // バイナリでファイル読込み std::ifstream ifs(FileName, std::ios::in | std::ios::binary); if (ifs.is_open()) { ifs.read(reinterpret_cast<char*>(&data.Value), sizeof(int)); ifs.read(data.Text, sizeof(char) * 10); ifs.close(); std::cout << data.Value; std::cout << data.Text; } // その他 std::ifstream ifs2(FileName, std::ios::in | std::ios::binary); if (ifs2.is_open()) { // ファイルが開いているかどうか bool isOpen = ifs2.is_open(); // ファイルサイズの取得 ifs2.seekg(0, std::ios::end); int size = ifs2.tellg(); ifs2.seekg(0); // 指定シーケンス位置の読込み char Str[10]; ifs2.seekg(sizeof(int)); ifs2.read(Str, sizeof(char) * 10); // 読込みに失敗したかどうか bool isBad = ifs2.bad(); // 格納されたストリーム バッファーのアドレス std::cout << ifs2.rdbuf(); // ストリームを閉じる ifs2.close(); } } |
OpenMode
ファイルを開くモードを指定します。
バイナリで読み書きする場合、ofstream.open(“filename”, std::ios::binary)の指定が必要。
詳しくは以下参照。
まとめ
思ったよりバイナリの入出力が簡単に行えますね。
ストリーム回りはC#と扱い方がほぼほぼ同じですんなりと頭に入りました。
実際の案件ではデータ構造がもっと複雑なので、色々と面倒ですが…。
コメント