我想更新现有的json文件。
这是示例json文件:
{
"Foo": 51.32,
"Number": 100,
"Test": "Test1"
}
程序日志:
Operation successfully performed
100
"Test1"
51.32
46.32
Done
看起来一切都按预期进行...
如果我将fstream更改为ifstream以便读取,稍后将ofstream写入,则可以正常工作...
我尝试使用调试器,并且我看到basic_ostream对象中的数据有误...但是我不知道为什么,我使用了来自已校正字符串(更新后的数据)的数据。知道有什么问题吗:-)?
您在这里遇到一些问题。
首先,命令json json_data(fs);
读取设置EOF
标志的文件末尾。在清除该标志之前,流将停止工作。
其次,文件指针位于文件末尾。如果要覆盖文件,则需要再次移至开头:
if (fs.is_open())
{
json json_data(fs); // reads to end of file
fs.clear(); // clear flag
fs.seekg(0); // move to beginning
不幸的是,这仍然不能解决所有问题,因为如果您写回的文件小于您读入的文件,则会在新数据的末尾标记一些旧数据:
std::cout << "Operation successfully performed\n";
std::cout << json_data.at("Number") << std::endl;
std::cout << json_data.at("Test") << std::endl;
std::cout << json_data.at("Foo") << std::endl;
json_data.at("Foo") = 4.32; // what if new data is smaller?
Json文件:
{
"Foo": 4.32, // this number is smaller than before
"Number": 100,
"Test": "Test1"
}} // whoops trailing character from previous data!!
在这种情况下,我只需要打开一个文件来读取然后再打开另一个文件来写入,该文件就不那么容易出错了,并表示打算覆盖所有内容。
就像是:
#include "json.hpp"
#include <iostream>
#include <fstream>
#include <string>
using json = nlohmann::json;
void readAndWriteDataToFile(std::string fileName) {
json json_data;
// restrict scope of file object (auto-closing raii)
if(auto fs = std::ifstream(fileName))
{
json_data = json::parse(fs);
std::cout << "Operation successfully performed\n";
std::cout << json_data.at("Number") << std::endl;
std::cout << json_data.at("Test") << std::endl;
std::cout << json_data.at("Foo") << std::endl;
}
else
{
throw std::runtime_error(std::strerror(errno));
}
json_data.at("Foo") = 4.32;
std::cout << json_data.at("Foo") << std::endl;
std::string json_content = json_data.dump(3);
if(auto fs = std::ofstream(fileName))
{
fs.write(json_content.data(), json_content.size());
std::cout << "Done" << std::endl;
}
else
{
throw std::runtime_error(std::strerror(errno));
}
}
int main()
{
try
{
std::string fileName = "C:/new/json1.json";
readAndWriteDataToFile(fileName);
}
catch(std::exception const& e)
{
std::cerr << e.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句