萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C++ 檔案流完整實戰:文字/二進制讀寫、隨機存取、複製檔案與最佳實務

C++ 檔案流類別體系

類別繼承用途預設開啟模式
ifstreamistream唯讀ios::in
ofstreamostream唯寫ios::out | ios::trunc
fstreamiostream讀寫ios::in | ios::out

開啟模式旗標 (ios::openmode)

旗標值說明
in0x01供讀取,檔案不存在失敗 (ifstream 預設)
out0x02供寫入,檔案不存在建立,存在則清空 (ofstream 預設)
ate0x04開啟後指標移至檔案末尾,可隨意移動
app0x08附加模式,寫入永遠在末尾,不可移動指標覆寫
trunc0x10截斷為零長度 (out 預設行為)
nocreate0x20檔案不存在則失敗
noreplace0x40檔案存在則失敗
binary0x80**二進位模式**,關閉換行符轉換,**讀寫二進位檔必須指定**
**組合範例**:fstream f("data.dat", ios::in | ios::out | ios::binary); 讀寫現有二進位檔。

文字檔讀寫:格式化運算子 << / >>

#include 
#include 
#include 

void WriteTextDemo() {
    std::ofstream ofs("demo.txt");
    ofs << std::setw(20) << "姓名:" << "張三" << '\n';
    ofs << std::setw(20) << "城市:" << "台北" << '\n';
    ofs.close(); // RAII 會自動關閉,顯式關閉亦可
}

void ReadTextDemo() {
    std::ifstream ifs("demo.txt");
    std::string label, value;
    while (ifs >> label >> value) { // 以空白分隔讀取
        std::cout << label << value << '\n';
    }
}

二進位檔讀寫:read / write / gcount

struct Record {
    int id;
    double score;
    char name[32];
};

void WriteBinary() {
    std::ofstream ofs("records.dat", std::ios::binary);
    Record r{1, 95.5, "Alice"};
    ofs.write(reinterpret_cast(&r), sizeof(Record));
    // 寫入多筆...
}

void ReadBinary() {
    std::ifstream ifs("records.dat", std::ios::binary);
    Record r;
    while (ifs.read(reinterpret_cast(&r), sizeof(Record))) {
        // gcount() 取得實際讀取位元組數 (處理檔案尾部不足一筆)
        std::cout << r.id << ' ' << r.name << ' ' << r.score << '\n';
    }
}
**鐵律**:二進位檔**必須**加 std::ios::binary**,且**只能用 read/write**,不可用 <</>>。

檔案指標隨機存取

std::fstream fs("data.bin", std::ios::in | std::ios::out | std::ios::binary);

// 讀取指標
fs.seekg(100, std::ios::beg); // 絕對位移 100 bytes from begin
fs.seekg(-20, std::ios::cur); // 相對目前位置往前 20
fs.seekg(0, std::ios::end);   // 移至末尾
std::streampos pos = fs.tellg(); // 取得目前讀取位置

// 寫入指標
fs.seekp(0, std::ios::beg);
fs.write(buf, len);

// 參照點:beg(0), cur(1), end(2)

完整範例:文字檔顯示、二進位檔複製

文字檔逐字元/逐行/區塊讀取三種寫法

// 1. 逐字元 get()
void PrintCharByChar(const char* path) {
    std::ifstream in(path);
    char c;
    while (in.get(c)) std::cout << c;
}

// 2. 逐行 getline() (文本模式自動處理 \r\n)
void PrintLineByLine(const char* path) {
    std::ifstream in(path);
    std::string line;
    while (std::getline(in, line)) std::cout << line << '\n';
}

// 3. 區塊 read() + gcount() (二進位/大檔通用)
void PrintBlock(const char* path) {
    std::ifstream in(path, std::ios::binary);
    char buf[4096];
    while (in.read(buf, sizeof(buf)) || in.gcount() > 0) {
        std::cout.write(buf, in.gcount());
    }
}

二進位檔案複製 (含大檔、進度條雛形)

bool CopyBinaryFile(const char* src, const char* dst, size_t bufSize = 1024*1024)
{
    std::ifstream in(src, std::ios::binary);
    if (!in) return false;
    std::ofstream out(dst, std::ios::binary);
    if (!out) return false;

    std::unique_ptr buf(new char[bufSize]);
    while (in.read(buf.get(), bufSize) || in.gcount() > 0) {
        out.write(buf.get(), in.gcount());
        if (!out) return false; // 磁碟滿等錯誤
    }
    return true;
}

資源管理與錯誤處理最佳實務

  1. RAII:區域變數 ifstream/ofstream/fstream 離開作用域自動 close()、釋放緩衝區。
  2. 狀態檢查:if (!fs) 或 if (fs.fail()),fs.good() 表示一切正常。
  3. 例外啟用:fs.exceptions(std::ios::failbit | std::ios::badbit); 讓 I/O 錯誤拋出 std::ios_base::failure。
  4. 二進位結構體對齊:跨平台/跨編譯器交換資料時,需 #pragma pack 或手動序列化,避免結構體填充位元組差異。
  5. 編碼:文字檔預設依區域設定,跨平台請明確指定 UTF-8 (C++20 std::filesystem::path、std::codecvt_utf8 或第三方庫)。

結語

C++ 檔案流核心在於:**選對類別 (ifstream/ofstream/fstream)、正確指定 binary 旗標、善用 RAII 自動管理資源、隨機存取靠 seekg/seekp/tellg/tellp**。文字檔用格式化運算子,二進位檔用 read/write/gcount。掌握這套機制,即可安全高效處理各類檔案 I/O 需求。

copyright © 萬盛學電腦網 all rights reserved