使用 `sourceFile.rdbuf()` 讀取二進位檔案並輸出,結果顯示亂碼。需轉為可識別的十六進位或 Base64 字串,且可逆向還原。
#include
#include
#include
// 需自行實現或使用庫:OpenSSL、Boost、C++23 std::base64
std::string base64_encode(const std::vector& data);
int main() {
std::ifstream file("binary.dat", std::ios::binary);
std::vector buffer((std::istreambuf_iterator(file)), {});
std::string b64 = base64_encode(buffer);
std::cout << b64; // 可安全存為文字檔、傳輸 JSON、XML
// 還原
std::vector decoded = base64_decode(b64);
std::ofstream out("restored.dat", std::ios::binary);
out.write(reinterpret_cast(decoded.data()), decoded.size());
}
std::string to_hex(const std::vector& data) {
static const char* hex = "0123456789ABCDEF";
std::string result;
result.reserve(data.size() * 2);
for (unsigned char b : data) {
result.push_back(hex[b >> 4]);
result.push_back(hex[b & 0xF]);
}
return result;
}
std::vector from_hex(const std::string& hexStr) {
std::vector data;
data.reserve(hexStr.size() / 2);
for (size_t i = 0; i < hexStr.size(); i += 2) {
unsigned char high = (hexStr[i] >= 'A') ? (hexStr[i] - 'A' + 10) : (hexStr[i] - '0');
unsigned char low = (hexStr[i+1] >= 'A') ? (hexStr[i+1] - 'A' + 10) : (hexStr[i+1] - '0');
data.push_back((high << 4) | low);
}
return data;
}
若只需複製檔案:
std::ifstream src("in.dat", std::ios::binary);
std::ofstream dst("out.dat", std::ios::binary);
dst << src.rdbuf(); // 高效、無轉換、完美還原
| 場景 | 推薦格式 | 理由 |
|---|---|---|
| JSON/XML/資料庫文字欄位存儲 | Base64 | 標準化、單行、URL 安全變體可用 |
| 除錯、日誌、人工檢視 | Hex | 直觀、易對照位元組 |
| 檔案複製、網路傳輸二進位協議 | 原始二進位 | 零開銷、最高效 |