首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 二進制檔案複製失敗:ofstream 必須指定 ios::binary 模式

     編輯:程式設計綜合問答

錯誤現象

使用 `ofstream out(filename); out.write(buffer, size);` 複製 `.exe` 等二進制檔案,輸出檔案比原檔多/少位元組、內容偏移 (如 0x70 處多一個 0x0D)。

根因

`ofstream` **預設為文本模式** (`ios::text`),Windows 下會將 `\n` (0x0A) 自動轉換為 `\r\n` (0x0D 0x0A),導致二進制資料被竄改、長度變長、校驗失效。

修正


std::ofstream out(filename, std::ios::binary); // ★ 關鍵:二進制模式
if (out) {
    out.write(reinterpret_cast(buffer), size);
}

完整複製範例 (C++17)


#include 
#include 
#include 

bool copy_binary(const std::string& src, const std::string& dst) {
    std::ifstream in(src, std::ios::binary | std::ios::ate);
    if (!in) return false;
    std::streamsize size = in.tellg();
    in.seekg(0, std::ios::beg);
    std::vector buffer(size);
    if (!in.read(buffer.data(), size)) return false;
    std::ofstream out(dst, std::ios::binary);
    if (!out) return false;
    out.write(buffer.data(), size);
    return out.good();
}

延伸:跨平台行尾差異

  • Windows 文本模式:`\n` ↔ `\r\n` 轉換。
  • Linux/macOS 文本模式:無轉換 (`\n` only)。
  • **二進制模式 (`ios::binary`) 所有平台均無轉換**,位元組完全一致。

鐵律:讀寫非文本檔 (圖片、執行檔、壓縮包、序列化資料) 必須加 `std::ios::binary`。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved