fstream を使ってバイナリファイルを操作する
このステップでは、C++ の fstream
クラスを使ってバイナリファイルを操作する方法を学びます。バイナリファイルは、データをそのままのバイナリ形式で保存します。これは、テキストファイルとは異なり、構造化データを効率的に保存するのに役立ちます。
binary_files.cpp
という新しい C++ ファイルを作成します。
touch ~/project/binary_files.cpp
binary_files.cpp
ファイルに次のコードを追加します。
#include <iostream>
#include <fstream>
#include <string>
// バイナリファイルの書き込みを示すための単純な構造体
struct Student {
int id;
char name[50];
double gpa;
};
void writeBinaryFile() {
std::fstream binaryFile("students.bin", std::ios::out | std::ios::binary);
if (!binaryFile) {
std::cerr << "Error opening file for writing!" << std::endl;
return;
}
// いくつかの学生レコードを作成する
Student students[3] = {
{1, "John Doe", 3.5},
{2, "Alice Smith", 3.8},
{3, "Bob Johnson", 3.2}
};
// 構造体全体をバイナリファイルに書き込む
binaryFile.write(reinterpret_cast<char*>(students), sizeof(students));
binaryFile.close();
std::cout << "Binary file written successfully!" << std::endl;
}
void readBinaryFile() {
std::fstream binaryFile("students.bin", std::ios::in | std::ios::binary);
if (!binaryFile) {
std::cerr << "Error opening file for reading!" << std::endl;
return;
}
Student students[3];
// 構造体全体をバイナリファイルから読み取る
binaryFile.read(reinterpret_cast<char*>(students), sizeof(students));
std::cout << "Student Records:" << std::endl;
for (int i = 0; i < 3; ++i) {
std::cout << "ID: " << students[i].id
<< ", Name: " << students[i].name
<< ", GPA: " << students[i].gpa << std::endl;
}
binaryFile.close();
}
int main() {
// バイナリファイルを書き込む
writeBinaryFile();
// バイナリファイルを読み取る
readBinaryFile();
return 0;
}
プログラムをコンパイルします。
g++ binary_files.cpp -o binary_files
実行可能ファイルを実行します。
./binary_files
出力例:
Binary file written successfully!
Student Records:
ID: 1, Name: John Doe, GPA: 3.5
ID: 2, Name: Alice Smith, GPA: 3.8
ID: 3, Name: Bob Johnson, GPA: 3.2
バイナリファイルに関する重要なポイント:
- バイナリモードで
std::ios::binary
フラグを使用する
- バイナリデータ用の
write()
と read()
メソッド
- 型間の変換に
reinterpret_cast
を使用する
- 構造化データを効率的に保存するのに役立つ
- データの正確なバイナリ表現を維持する
バイナリファイルを、正確なブループリントのように考えることができます。メモリ内のデータのままをそのまま保存し、テキスト変換は行いません。