代码示例:
int main()
{
std::ifstream file("./outfile.json");
file.seekg(0,std::ios::end);
auto size = file.tellg();
file.seekg(0);
std::string content;
content.resize(static_cast<size_t>(size));
file.read(&content[0],size);
std::cout<<content<<std::endl;
nlohmann::json j = nlohmann::json::parse(content);
std::cout << j.dump(12) << std::endl;
std::cout << j.dump() << std::endl;
return 0;
}
ifstream::seekg()
是为打开文件设置文件指针的位置,在c++里进行了重载操作。std::ios::end
为打开文件的末尾,file.seekg(0,std::ios::end)
为从文件末尾的指针位置进行偏移,偏移为0,所以将此时的文件指针位置设置为了末尾。然后通过file.tellg()
获取文件指针位置,即可得到文件大小。获取文件大小后,文件从开头开始读取,需要将文件指针置为0,file.seekg(0)
将文件指针置为了0。