使用 `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);
}
#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();
}
鐵律:讀寫非文本檔 (圖片、執行檔、壓縮包、序列化資料) 必須加 `std::ios::binary`。