首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

C++ 檔案流操作完全指南:讀寫、複製、編碼與效能優化

     編輯:C++ 入門

核心類別速查

基本操作範例

寫入檔案(文字模式)

#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::ifstream輸入檔案流std::istream
std::ofstream輸出檔案流std::ostream
std::fstream雙向檔案流std::iostream

C++23 展望:std::print、std::format、std::filesystem::file_size

格式化輸出不再需 iostream 操作子鏈,std::print("{}", value) 更簡潔、型別安全、效能更好。

掌握 fstream 核心模式、二進位/文字差異、RAII 慣用語與大檔案優化策略,能輕鬆應對從配置檔讀寫到高吞吐資料處理的所有檔案 I/O 需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
議題最佳實踐
檔案開啟模式明確指定 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