gpt4 book ai didi

c++ - QFileSystemWatcher:检测文件是否已刷新

转载 作者:太空狗 更新时间:2023-10-29 23:00:13 26 4
gpt4 key购买 nike

我有一个 QT 应用程序需要知道特定文件中的新数据何时可用。所以我使用了 QFileSystemWatcher 并将 fileChanged 信号连接到一个函数,该函数将在发生更改时发送消息。

问题是 fileChanged 信号不会在另一个应用程序刷新此文件时发出,而只会在它关闭文件后发出。

然而,QFileSystemWatcher documentation说这个信号是“当指定路径的文件被修改、重命名或从磁盘中删除时”发出的。也许我错过了什么; modified 中包含哪些更改?如果不包括刷新,我如何检测新数据何时写入文件?

这是源代码:

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();

return a.exec();
}

主窗口.h

#include <QFileSystemWatcher>
#include <QMainWindow>

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

public slots:
void fileChangedEvent(const QString & path);

private:
QFileSystemWatcher * watcher;
};

主窗口.cpp

#include "mainwindow.h"

MainWindow::MainWindow()
{
watcher = new QFileSystemWatcher();
connect(watcher, SIGNAL(fileChanged(QString)), this, SLOT(fileChangedEvent(QString)));
watcher->addPath("path to file");
}

void MainWindow::fileChangedEvent(const QString & path)
{
qDebug() << path;
}

MainWindow::~MainWindow()
{
if(watcher!=NULL)
{
delete watcher;
watcher=NULL;
}
}

这是更改文件的另一个应用程序的代码(这是第 3 方应用程序,所以我无法更改它以与之同步):

#include <fstream>

int main () {

std::ofstream outfile ("path to file");

for (int n=0; n<100; ++n)
{
outfile << n;
outfile.flush();
}
outfile.close();

return 0;
}

fileChanged() 信号仅在 std::ofstream outfile ("path to file");outfile.close(); 被调用而不是在 outfile.flush();

之后

最佳答案

在 Windows 上,似乎 fileChanged 信号在文件的时间戳更改时发出,这发生在文件关闭时 (std::ofstream::close() ) 但不是(至少在 Windows 上)刷新时 (std::ofstream::flush())。为了测试它,我在每次写入文件后(在调用 std::ofstream::flush() 之后)使用以下函数显式更新了文件的时间戳:

#include <ctime>
#include <sys/stat.h>
#ifdef _WIN32
#include <sys/utime.h>
#else
#include <utime.h>
#endif

bool UpdateFileTimestamp(std::string fileName) {
struct stat fstat;
struct utimbuf new_time;

if (0 != stat(fileName.c_str(), &fstat))
return false;

new_time.actime = fstat.st_atime;
new_time.modtime = time(NULL);
if (0 != utime(fileName.c_str(), &new_time))
return false;

return true;
}

它奏效了。 fileChanged 信号按预期发出。

关于c++ - QFileSystemWatcher:检测文件是否已刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34267516/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com