核心類與方法
- `std::string`:動態字符串,自動內存管理
- `std::ifstream`:輸入文件流
- `std::ofstream`:輸出文件流
- `std::fstream`:雙向文件流
按行讀取文件
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main() {
ifstream in("input.txt");
ofstream out("output.txt");
string line;
while (getline(in, line)) { // 返回流對象,EOF 時轉為 false
cout << "Read: " << line << '\n';
out << line << '\n'; // 寫入並換行
}
// 或者讀取整個文件
in.clear(); in.seekg(0);
string content((istreambuf_iterator(in)), istreambuf_iterator());
cout << "Full content size: " << content.size() << '\n';
}
字符串核心操作
| 操作 | 方法 | 示例 |
| 查找子串 | `find(s)` / `rfind(s)` | `pos = str.find("good")` |
| 截取子串 | `substr(pos, len)` | `left = str.substr(0, pos)` |
| 字符串長度 | `size()` / `length()` | `len = str.size()` |
| C 風格指針 | `c_str()` / `data()` | `fp = fopen(str.c_str(), "r")` |
| 字符訪問 | `[]` / `at()` | `ch = str[0]` |
| 拼接 | `+` / `append()` | `s = a + b` |
| 比較 | `==` `<` `compare()` | `if (a == b)` |
文件流打開模式
ofstream out("file.txt", ios::out | ios::trunc); // 覆蓋寫入(默認)
ofstream app("file.txt", ios::out | ios::app); // 追加寫入
ifstream in("file.txt", ios::in); // 讀取
fstream io("file.txt", ios::in | ios::out); // 讀寫
fstream bin("data.bin", ios::in | ios::out | ios::binary); // 二進制
完整示例:讀取、查找、寫入
int main() {
string inFile = "test.txt", outFile = "test1.txt";
ifstream in(inFile);
ofstream out(outFile);
string line;
while (getline(in, line)) {
// 查找 "is" 位置
size_t pos = line.find("is");
if (pos != string::npos) {
cout << "Found at: " << pos << '\n';
}
out << line << '\n';
}
// 字符串寫入文件
string data = "cjc is a student.";
out.write(data.c_str(), data.size()); // 二進制寫入,無格式化
return 0;
}
關鍵區別:`write` vs `<<`
- `out << str`:格式化輸出,可能受 locale 影響
- `out.write(ptr, len)`:二進制塊寫入,精確控制字節,高性能
最佳實踐
- 打開文件後檢查 `if (!in)` 或 `in.is_open()`
- 大文件讀取用 `getline` 逐行處理,避免一次性載入內存
- 二進制數據用 `write`/`read` + `c_str()`/`data()`
- RAII:流對象離開作用域自動關閉,無需手動 `close()`
- 異常安全:啟用 `exceptions()` 或檢查 `fail()`/`bad()`
C++ 文件流與 string 結合提供了強大、安全、高效的文本/二進制處理能力,掌握 `getline`、`find`/`substr`、`c_str()` 互轉、二進制讀寫等核心技能,足以應對絕大多數文件處理場景。
- 上一篇文章: C++ Primer 學習筆記:運算符重載基礎——定義規則與限制
- 下一篇文章: 斜率優化 DP 專題:BZOJ 1911 特別行動隊(APIO 2010)
Copyright ©
程式碼之家 All Rights Reserved