读取文件代码:
std::unique_ptr<std::string> ReadFileContent(const std::string &path) {
std::ifstream ifs;
ifs.open(path, std::ifstream::binary);
if (!ifs.is_open()) {
return nullptr;
}
return std::unique_ptr<std::string>(
new std::string(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>()));
}
在mac运行得到 string 长度为文件长度,但在win平台运行,string长度非常小
原因是ifstream默认以文本模式打开,在win平台上 0x1A
被标记为文件结尾(EOF),所以文件中包含 0x1A
则会终止读取。
解决方案:
- fopen 方式读取
fopen(path, "rb");
- ifstream 设置以binary方式读取:
ifs.open(path, std::ifstream::binary);
参考:https://stackoverflow.com/questions/61028068/why-does-reading-a-file-to-a-stdstring-have-a-wrong-length-on-windows