C++ 比较JSON::Value变量中的数据,然后更新为文件
我试图通过在运行时提供文件名将数据更新为两个JSON文件 这是updateTOFile函数,它将存储在JSON变量中的数据更新为两个不同线程中的两个不同数据C++ 比较JSON::Value变量中的数据,然后更新为文件,c++,C++,我试图通过在运行时提供文件名将数据更新为两个JSON文件 这是updateTOFile函数,它将存储在JSON变量中的数据更新为两个不同线程中的两个不同数据 void updateToFile() { while(runInternalThread) { std::unique_lock<std::recursive_mutex> invlock(mutex_NodeInvConf);
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();
}
}
void updateToFile()
{
while(运行内部线程)
{
std::unique_lock invlock(mutex_NodeInvConf);
文件*pFile;
std::string conff=NodeInvConfiguration.toStyledString();
pFile=fopen(filename.c_str(),“wb”);
std::ifstream文件(文件名);
fwrite(conff.c_str(),sizeof(char),conff.length(),pFile);
fclose(pFile);
sync();
}
}
线程1:std::threadnt(&NodeList::updateToFile,this)代码>
线程2:
std::threadit(&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();
}
}
}
void updateToFile()
{
std::前面的字符串;
while(运行内部线程)
{
std::unique_lock invlock(mutex_NodeInvConf);
std::string conf=NodeInvConfiguration.toStyledString();
if(conf!=上一个)
{
//TODO:错误处理丢失,如在OP中
std::流文件(文件名);
file.write(conf.c_str(),conf.length());
file.close();
previous=std::move(conf);
sync();
}
}
}
然而,这种循环中的持续轮询可能效率低下。您可以添加Sleep
s以减少勤奋。另一种选择是,如果它已更改,则通过NodeInvConfiguration
自身进行跟踪,并在存储时清除该标志。离题:我从未见过C++11和C如此随意的混合。似乎这都是自学的?可能使用流的和ifstream
而不是C风格的文件句柄。您可能需要打开文件,读取内容并将其与需要写入的数据进行比较。如果数据没有变化,您只需打印关于数据相同的日志,如果没有,则覆盖内容。还是我遗漏了什么?@Mahesh你说得对。但我想问的是怎么做??可以用我的代码演示同样的情况。@Sachin我不明白:“…将把JSON变量中存储的数据更新为两个不同的”-两个不同的什么?@TEDLYNGOM两个不同的文件”另一个选项是,如果节点配置本身已更改,则通过节点配置本身进行跟踪,并在存储时清除该标志”。怎么做?我不知道,你没有发。