首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在磁盘上的JSON文件中追加JSON数组,每秒钟使用C++

问在磁盘上的JSON文件中追加JSON数组,每秒钟使用C++
EN

Stack Overflow用户
提问于 2013-04-07 18:45:08
回答 1查看 1.1K关注 0票数 1

这是我在这里的第一篇帖子,所以请容忍我。

我在互联网上到处寻找答案,但我一直无法解决我的问题,所以我决定在这里写一篇文章。

我试图使用C++和JZON将JSON数组写入(附加)到文件中,每秒钟写一次。JSON文件最初是由“准备”函数编写的。然后,每秒钟调用另一个函数将数组添加到JSON文件中,并每秒钟向数组追加一个新对象。

我尝试过很多事情,其中大部分都导致了各种各样的问题。我最近的尝试给了我最好的结果,这是我已经包括在下面的代码。但是,我采用的方法效率很低,因为我每秒钟都要编写一个完整的数组。随着数组的增长,CPU的使用受到了很大的影响,但对内存的影响并不像我最初预期的那样大。

我真正想要做的是逐行添加到磁盘上JSON文件中包含的现有数组,而不是每秒钟从JSON对象中清除整个数组并重写整个文件。

我希望在这个网站上的一些天才将能够指出我的正确方向。

先谢谢你。

这是我的代码:

代码语言:javascript
复制
//Create some object somewhere at the top of the cpp file
Jzon::Object jsonFlight;
Jzon::Array jsonFlightPath;
Jzon::Object jsonCoordinates;
int PrepareFlight(const char* jsonfilename) {
  //...SOME PREPARE FUNCTION STUFF GOES HERE...
  //Add the Flight Information to the jsonFlight root JSON Object
  jsonFlight.Add("Flight Number", flightnum);
  jsonFlight.Add("Origin", originicao);
  jsonFlight.Add("Destination", desticao);
  jsonFlight.Add("Pilot in Command", pic);
  //Write the jsonFlight object to a .json file on disk. Filename is passed in as a param    of the function.
  Jzon::FileWriter::WriteFile(jsonfilename, jsonFlight, Jzon::NoFormat);
  return 0;
}
int UpdateJSON_FlightPath(ACFT_PARAM* pS, const char* jsonfilename) {
  //Add the current returned coordinates to the jsonCoordinates jzon object
  jsonCoordinates.Add("altitude", pS-> altitude);
  jsonCoordinates.Add("latitude", pS-> latitude);
  jsonCoordinates.Add("longitude", pS-> longitude);
  //Add the Coordinates to the FlightPath then clear the coordinates.
  jsonFlightPath.Add(jsonCoordinates);
  jsonCoordinates.Clear();
  //Now add the entire flightpath array to the jsonFlight object.
  jsonFlight.Add("Flightpath", jsonFlightPath);
  //write the jsonFlight object to a JSON file on disk.
  Jzon::FileWriter::WriteFile(jsonfilename, jsonFlight, Jzon::NoFormat);
  //Remove the entire jsonFlighPath array from the jsonFlight object to avoid duplicaiton next time the function executes.
  jsonFlight.Remove("Flightpath");
  return 0;
}
EN

回答 1

Stack Overflow用户

发布于 2013-08-02 05:10:02

确保你可以自己做“平面文件”的存储。但这是一个需要数据库的症状。一些很轻的东西,比如SQLite,或者是中等重量的,开源的,比如MySQL,FireBird,或者PostgreSQL.

但关于你的问题:

1)关闭]括号,只需打开并附加文件--但如果不正确关闭该文件,它将被损坏&需要修复才能读懂。

2)当前的选项--每次写入一个完整的文件--也无法避免数据丢失,因为当您“打开覆盖”时,您丢失了之前存储在文件中的所有数据。这里的解决方法是在开始编写之前将旧文件重命名为备份。

您还应该使用第一个选项来备份您的文件。(比如每天一次)。否则,数据丢失很可能最终发生--对Ctrl、功耗、程序错误或系统崩溃。

当然,如果您使用任何SQLlite、MySQL、Firebird或PostgreSQL,所有的数据完整性问题都将为您处理。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15866311

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档