| 類別 | 用途 | 繼承 |
std::ifstream | 輸入檔案流 | std::istream |
std::ofstream | 輸出檔案流 | std::ostream |
std::fstream | 雙向檔案流 | std::iostream |
基本操作範例
寫入檔案(文字模式)
#include
#include
void writeFile() {
std::ofstream out("d.txt", std::ios::out | std::ios::trunc);
if (!out) throw std::runtime_error("Cannot open file for writing");
std::string content = u8"床前明月光\n疑是地上霜\n舉頭望明月\n低頭思故鄉\n";
out << content << std::endl;
// RAII 自動關閉並 flush
}
讀取檔案(逐行)
void readFile() {
std::ifstream in("a.txt");
if (!in) throw std::runtime_error("Cannot open file for reading");
std::string line;
while (std::getline(in, line)) {
std::cout << line << '\n';
}
}
檔案複製(文字模式,自動處理換行符轉換)
void copyFileText() {
std::ifstream in("a.txt");
std::ofstream out("b.txt");
std::string line;
while (std::getline(in, line)) {
out << line << '\n'; // 統一用 '\n',ofstream 會依平台轉換
}
std::cout << "複製完成\n";
}
二進位檔案複製(高效、保持位元組完全一致)
void copyFileBinary() {
std::ifstream in("source.bin", std::ios::binary);
std::ofstream out("dest.bin", std::ios::binary);
out << in.rdbuf(); // 直接複製 streambuf,最快、最省記憶體
// 或手動緩衝區:
// constexpr size_t BUFSIZE = 64 * 1024;
// char buf[BUFSIZE];
// while (in.read(buf, BUFSIZE)) out.write(buf, in.gcount());
// out.write(buf, in.gcount());
}
進階實戰:篩法判斷質數(結合檔案 I/O)
void sievePrimeCheck() {
constexpr int LIMIT = 10000;
std::vector isPrime(LIMIT, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i < LIMIT; ++i)
if (isPrime[i])
for (int j = i * i; j < LIMIT; j += i)
isPrime[j] = false;
std::ifstream in("c.txt");
int n;
while (in >> n) {
if (n > 1 && n < LIMIT)
std::cout << n << " is " << (isPrime[n] ? "" : "not ") << "a prime.\n";
}
}
關鍵細節與避坑指南
| 議題 | 最佳實踐 |
| 檔案開啟模式 | 明確指定 std::ios::binary 避免 Windows 換行符轉換(\n↔\r\n) |
| 編碼處理 | 文字檔建議統一 UTF-8,讀寫時搭配 std::codecvt_utf8 (C++11) 或第三方庫(ICU, utf8cpp) |
| 錯誤狀態檢查 | 用 if (stream) 或 stream.fail(),bad() 為不可恢復錯誤,fail() 含格式錯誤 |
| 大檔案效能 | rdbuf() 直接複製、mmap (POSIX) / MapViewOfFile (Windows)、非同步 I/O |
| RAII 管理 | 區塊結束自動關閉,不要 手動 close() 除非需提前釋放鎖 |
| 路徑處理 | C++17 std::filesystem::path 跨平台路徑操作,支援 UTF-8 |
C++23 展望:std::print、std::format、std::filesystem::file_size
格式化輸出不再需 iostream 操作子鏈,std::print("{}", value) 更簡潔、型別安全、效能更好。
掌握 fstream 核心模式、二進位/文字差異、RAII 慣用語與大檔案優化策略,能輕鬆應對從配置檔讀寫到高吞吐資料處理的所有檔案 I/O 需求。
- 上一篇文章: C++ 指標與參考的本質差異:從語法到效能的深度剖析
- 下一篇文章: C++ enum 枚舉類型完全解析:基礎語法、作用域與現代化用法
Copyright ©
程式碼之家 All Rights Reserved