在 Xcode 中將 JPG 圖片數據寫入本地文件後,文件格式似乎發生變化,導致後續 C++ 讀取時提示「非 JPG 文件」。
文本模式 vs 二進制模式 是經典坑:
\n (0x0A) 會被轉換為 \r\n (0x0D 0x0A),二進制數據中若包含 0x0A 會被破壞。<< 運算符輸出二進制數據,同樣會出問題。// 錯誤示範:使用文本模式或流運算符寫二進制
ofstream out("image.jpg"); // 缺少 ios::binary
out << binaryData; // 運算符<< 格式化輸出,不適合二進制
#include <fstream>
#include <vector>
bool writeJpg(const char* path, const unsigned char* data, size_t len) {
std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
if (!ofs) return false;
ofs.write(reinterpret_cast(data), static_cast(len));
return ofs.good();
}
// 讀取同理
std::vector readJpg(const char* path) {
std::ifstream ifs(path, std::ios::binary | std::ios::ate);
if (!ifs) return {};
size_t len = ifs.tellg();
ifs.seekg(0);
std::vector buf(len);
ifs.read(reinterpret_cast(buf.data()), len);
return buf;
}
FF D8 FF)。std::string 存儲二進制數據(string 以 \0 結尾,截斷數據)。請用 std::vector<unsigned char> 或 std::string 配合 data()/size()。核心原則:**二進制數據全程二進制模式,拒絕任何格式化輸出/輸入操作。**