c++ - 在 NFS 挂载上读取文件时出现奇怪的 C++ 行为
问题描述
我已经编写了一些 C++ 代码,它们在 Linux 上使用 nlohmann::json 库读取 json 文件。它工作正常。
但是,当我在 WSL 中安装 NFS 磁盘时,相同的代码会失败(json 文件在随机位置存在解析问题,例如 line1 char 8173)。在 WSL2 中,NFS 磁盘首先作为驱动器挂载在 windows 中,然后在 linux 中使用 drvfs 挂载。我可以使用终端读取我在其上写入文件(文件被视为 root:root 777)。但是我不明白为什么一些 C++ 函数可以很好地读取文件内容而其他一些函数会检索损坏的数据。
ifstream input(filePath, ios::binary); // binary and text mode dives same result
if (!input.is_open())
{
return;
}
//Json::parse(input, nullptr, true); // KO
//Json::parse(read1(input), nullptr, true); // KO
Json::parse(read2(input), nullptr, true); // OK
string read1(ifstream& input)
{
stringstream buffer;
buffer << input.rdbuf();
string content = buffer.str();
return content;
}
string read2(ifstream& input)
{
input.seekg(0, std::ios::end);
size_t size = input.tellg();
string content(size, ' ');
input.seekg(0);
input.read(&content[0], size);
return content;
}