ファイル操作したい(std::fstream
)
1#include <fstream> // std::fstream
2#include <sstream> // std::stringstream
3
4// 連続してファイル名を生成したい場合、
5// ファイル名が重複しないように工夫する
6G4int run_id = "ランID";
7G4int event_id = "イベントID";
8
9// ファイル名を生成する
10std::stringstream filename;
11filename << "run" << std::setfill('0') << std::setw(5) << run_id;
12filename << "event" << std::setfill('0') << std::setw(5) << event_id;
13filename << ".csv";
14
15// ファイルを追記モードで作成する
16std::ofstream file(filename.c_str(), std::ios::app);
17
18// ファイルが開けなかった場合の処理
19if (!file.is_open())
20{
21 G4cerr << "Failed to open file: " << filename << G4endl;
22 return;
23};
24
25// ファイルに文字列を追加する
26G4cout << "File opened: " << filename << G4endl;
27file << "CSV文字列1" << "\n";
28file << "CSV文字列2" << "\n";
29file << "CSV文字列3" << "\n";
30
31// ファイルを閉じる
32file.close();
std::stringstream
で、ファイル名を作成しています。
std::fstream
でファイル操作しています。