What is the proper way to use inotify?

后端 未结 4 954
一生所求
一生所求 2020-11-30 02:22

I want to use the inotify mechanism on Linux. I want my application to know when a file aaa was changed. Can you please provide me with a sample ho

4条回答
  •  自闭症患者
    2020-11-30 02:53

    Since the initial question seems to mention Qt as a tag as noted in several comments here, search engines may have lead you here.

    If somebody want to know how to do it with Qt, see http://doc.qt.io/qt-5/qfilesystemwatcher.html for the Qt-version. On Linux it uses a subset of Inotify, if it is available, see explanation on the Qt page for details.

    Basically the needed code looks like this:

    in mainwindow.h add :

    QFileSystemWatcher * watcher;
    private slots:
        void directoryChanged(const QString & path);
        void fileChanged(const QString & path);
    

    and for mainwindow.cpp:

    #include 
    #include 
    
    watcher = new QFileSystemWatcher(this);
    connect(watcher, SIGNAL(fileChanged(const QString &)), this, SLOT(fileChanged(const QString &)));
    connect(watcher, SIGNAL(directoryChanged(const QString &)), this, SLOT(directoryChanged(const QString &)));
    watcher->addPath("/tmp/"); // watch directory
    watcher->addPath("/tmp/a.file");  // watch file
    

    also add the slots in mainwindow.cpp which are called if a file/directory-change is noticed:

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

提交回复
热议问题