# Basic fstream --- `fstream` 是建立在 `iostream` 上來實作的 所以所有 `iostream` 的操作都可以在 `fstream` 上使用 舉例 ```cpp= ifstream fin("in.txt"); ofstream fout("out.txt"); string str; while(fin >> str) fout << "hello, " << str << endl; ``` 由此可以知道 `ifstream` 是讀入,`ofstream` 是輸出 雖然 `fstream` 有自己的讀寫函數 但是 `operator<<`、`oeprator>>` 太好用了:poop:,所以用不太到 然後其實 `fstream` 只要是"文字檔"都可以開 以下為合法操作 ```cpp= ofstream cpp("C++.cpp"); ofstream py("Python.py"); cpp << "#include<iostream>\nusing namespace std;\n"; py << "import sys\nimport path"; ``` 另外還可以開二進位檔 不過出題用不到,所以我不會:poop: ([紫大](https://www.flag.com.tw/books/product/F0713)有) 然後要注意雖然 `fstream` 的`destructor` 有關閉並處存檔案 但是還是要記得用 `.close()` 養成習慣在檔案用不到時關閉 可以避免檔案開起衝突 最後通常因為看這個是為了出題 所以我也放上出題的模板:poop: ```cpp= #pragma GCC optimize("O2") #include <bits/stdc++.h> #define f first #define s second #define pii pair<int, int> using namespace std; const string id = "a001"; // problem id vector<int> num{100, 10000, 1000000}; // number of test data vector<pii> range{{100, 1000}, {10000, 100000}, {100000, 1000000}}; // range: [l, r] fstream fin, fout; string fn(int x) { return string{char('0' + x / 10), char('0' + x % 10)}; } int solve(int x) { /* code here to solve */ /* return solution */ /* or just use "fout << ans" */ } int main() { srand(time(0)); mt19937 gen(rand()); for (int i = 0; i < num.size(); i++) { uniform_int_distribution<int> dis(range[i].f, range[i].s); fin.open(id + "_" + fn(i) + ".in", ios::out); fout.open(id + "_" + fn(i) + ".out", ios::out); /* ---------- data ----------*/ for (int j = 0; j < num[i]; j++) { /* input, output data e.g. auto rd = dis(gen); fin << rd << '\n'; fout << solve(rd) << '\n'; */ } fin.close(); fout.close(); } return 0; } ``` [最後按照慣例](http://cplusplus.com/reference/fstream/) --- >[color=#0ff00f][name=revcoding]