プログラム実行中に生成されるデータは一時的なものであり、終了時に解放されます。これを永続化するにはファイルへの保存が必要です。C++では<fstream>ヘッダを用いてファイル操作を行います。
ファイルは以下の2種類に分類されます:
- テキストファイル:ASCIIコード形式で保存され、人間が読める形式
- バイナリファイル:バイト列として保存され、通常は人間が直接読めない形式
ファイル操作には以下の3つのストリームクラスが使用されます:
ofstream:書き込み専用ifstream:読み込み専用fstream:読み書き両用
1. テキストファイルの操作
1.1 書き込み
テキストファイルへの書き込み手順は以下の通りです:
#include <fstream>をインクルードofstreamオブジェクトを作成open()でファイルを開く(モード指定)<<演算子でデータを書き込むclose()でファイルを閉じる
主なファイルオープンモード:
| モード | 説明 |
|---|---|
ios::in | 読み込み用に開く |
ios::out | 書き込み用に開く |
ios::ate | ファイル末尾から開始 |
ios::app | 追記モード |
ios::trunc | 既存ファイルを空にする |
ios::binary | バイナリモード |
モードはビットOR(|)で組み合わせ可能(例:ios::out | ios::binary)。
#include <fstream>
using namespace std;
void writeTextFile() {
ofstream writer;
writer.open("info.txt", ios::out);
writer << "名前:山田太郎\n";
writer << "年齢:25\n";
writer << "スコア:95\n";
writer.close();
}
1.2 読み込み
テキストファイルの読み込み手順:
#include <fstream>をインクルードifstreamオブジェクトを作成open()でファイルを開き、is_open()で成功を確認- 適切な方法でデータを読み取る
close()でファイルを閉じる
代表的な読み取り方法:
#include <fstream>
#include <string>
using namespace std;
void readTextFile() {
ifstream reader("info.txt");
if (!reader.is_open()) return;
// 方法1: スペース区切りで単語単位読み取り
string word;
while (reader >> word) {
cout << word << '\n';
}
reader.clear(); reader.seekg(0);
// 方法2: 行単位で文字配列に読み取り
char line[256];
while (reader.getline(line, sizeof(line))) {
cout << line << '\n';
}
reader.clear(); reader.seekg(0);
// 方法3: 行単位でstringに読み取り(推奨)
string lineStr;
while (getline(reader, lineStr)) {
cout << lineStr << '\n';
}
reader.close();
}
2. バイナリファイルの操作
バイナリファイルを扱う際は、オープンモードに ios::binary を必ず指定します。
2.1 書き込み
write() メンバ関数を使用してメモリ上のデータをそのままファイルに書き込みます。
プロトタイプ:ostream& write(const char* buffer, streamsize size);
#include <fstream>
using namespace std;
struct Employee {
char name[64];
int id;
};
void writeBinaryFile() {
ofstream binWriter("employee.dat", ios::binary);
Employee emp = {"佐藤花子", 1001};
binWriter.write(reinterpret_cast<const char*>(&emp), sizeof(emp));
binWriter.close();
}
2.2 読み込み
read() メンバ関数でファイルからバイト列をメモリに読み込みます。
プロトタイプ:istream& read(char* buffer, streamsize size);
#include <fstream>
#include <iostream>
using namespace std;
void readBinaryFile() {
ifstream binReader("employee.dat", ios::binary);
if (!binReader.is_open()) return;
Employee emp;
binReader.read(reinterpret_cast<char*>(&emp), sizeof(emp));
cout << "名前: " << emp.name << "\nID: " << emp.id << '\n';
binReader.close();
}