比较 JSON::Value 变量中的数据,然后更新到文件

compare data in a JSON::Value variable and then update to file

本文关键字:然后 更新 文件 数据 JSON Value 变量 比较      更新时间:2023-10-16

我正在尝试通过在运行时提供文件名来将数据更新为两个 JSON 文件。

这是 updateTOFile 函数,它将存储在 JSON 变量中的数据更新为两个不同线程中的两个不同的数据。

void updateToFile()
{
while(runInternalThread)
{
std::unique_lock<std::recursive_mutex> invlock(mutex_NodeInvConf);
FILE * pFile;
std::string conff =  NodeInvConfiguration.toStyledString();
pFile = fopen (filename.c_str(), "wb");
std::ifstream file(filename);
fwrite (conff.c_str() , sizeof(char), conff.length(), pFile);
fclose (pFile);
sync();
}
}

主题 1:
std::thread nt(&NodeList::updateToFile,this);

话题 2:
std::thread it(&InventoryList::updateToFile,this);

现在,即使上次执行没有数据更改,它也会更新文件。我想仅在与以前存储的文件相比有任何变化时才更新文件。如果没有变化,那么它应该打印数据是相同的。 任何人都可以帮忙吗? 谢谢。

您可以在编写之前检查它是否已更改。

void updateToFile()
{
std::string previous;
while(runInternalThread)
{
std::unique_lock<std::recursive_mutex> invlock(mutex_NodeInvConf);
std::string conf =  NodeInvConfiguration.toStyledString();
if (conf != previous)
{
// TODO: error handling missing like in OP
std::ofstream file(filename);
file.write (conf.c_str() , conf.length());
file.close();
previous = std::move(conf);
sync();
}
}
}

然而,这种循环中的持续轮询可能是低效的。您可以添加Sleep以使其不那么勤奋。另一种选择是通过NodeInvConfiguration本身进行跟踪,如果它已更改并在存储时清除该标志。