#include <fstream>ofstream(寫),模式 ios::out。ifstream(讀),模式 ios::in。fstream,模式 ios::in | ios::out。ofstream outfile("data.txt", ios::out);
if (!outfile) { cerr << "open error!"; exit(1); }
for (int i = 0; i < 10; ++i) {
int x; cin >> x;
outfile << x << '\n'; // 像用 cout 一樣
}
outfile.close(); // 可選,析構時自動關閉
ifstream infile("data.txt", ios::in);
if (!infile) { cerr << "open error!"; exit(1); }
int x, maxv = -1e9;
while (infile >> x) { // 類似 cin,遇 EOF 為 false
if (x > maxv) maxv = x;
}
infile.close();
cout << "Max: " << maxv << '\n';
outfile/infile)用於操作,而非文件名字符串。ios::out 會截斷文件(清空),追加用 ios::app。ios::binary,配合 read()/write()。seekg()/seekp(),tellg()/tellp()。fail(), bad(), eof(), good()。struct Student { int id; char name[20]; double score; };
Student stu[3] = {{1,"Alice",92.5},{2,"Bob",87.0},{3,"Carol",95.5}};
// 寫二進制
ofstream ofs("stu.dat", ios::out | ios::binary);
ofs.write(reinterpret_cast(stu), sizeof(stu));
ofs.close();
// 讀二進制
Student read_stu[3];
ifstream ifs("stu.dat", ios::in | ios::binary);
ifs.read(reinterpret_cast(read_stu), sizeof(read_stu));
ifs.close();
iostream 風格操作,類型安全、可擴展。這是 C++ 文件 I/O 的基礎模板,掌握後可處理絕大多數數據持久化需求。