c++qtqtcoreqt-signalsqfilesystemwatcher

Monitoring file integrity


I would like to write a simple application that tells me when a file has been modified.

Does the <QFileSystemWatcher> class only monitor changes when the program is running?

If so, are there any other classes that I can use for file integrity monitoring?


Solution

  • You could run md5sum, etc. with QProcess initially and then for the changed signals and compare.

    The alternative is to read all the file in or mmap and create your hash with QCryptoGraphicHash.

    Either way, you would do this initially and then in the signal handlers, a.k.a. slots once the connection is properly made in your QObject subclass.

    #include <QObject>
    #include <QFileSystemWatcher>
    
    class MyClass : public QObject
    {
        Q_OBJECT
        public:
            explicit MyClass(QObject *parent = Q_NULLPTR)
                : QObject(parent)
            {
                // ...
                connect(m_fileSystemWatcher, SIGNAL(fileChanged(const QString&)), SLOT(checkIntegrity(const QString&)));
                // ...
            }
    
        public slots:
            void checkIntegrity(const QString &path)
            {
                // 1a. Use QProcess with an application like md5sum/sha1sum
                // OR
                // 1b. Use QFile with readAll() QCryptoGraphicsHash
                // 2. Compare with the previous
                // 3. Set the current to the new
            }
    
        private:
            QFileSystemWatcher m_fileSystemWatcher;
    };
    

    Disclaimer: This is obviously not in any way tested, whatsoever, but I hope it demonstrates the concept.