The Qfilesystemwatcher of QT

Source: Internet
Author: User

Briefly

The Qfilesystemwatcher class is used to provide an interface for monitoring file and directory modifications.

Qfilesystemwatcher monitors file and directory changes in the file system by monitoring the list of specified paths.

Call the Addpath () function to monitor a specific file or directory. If you need to monitor multiple paths, you can use Addpaths (). Remove the existing path by using the Removepath () and removepaths () functions.

Qfilesystemwatcher checks each path that is added to it, the files that have been added to the qfilesystemwatcher can be accessed using the file () function, and the directory is accessed using the directories () function.

A filechanged () signal is emitted when a file is modified, renamed, or deleted from disk. Similarly, when a directory or its contents are modified or?? When deleted, the directorychanged () signal is emitted. Note: Once the file is renamed or deleted from the hard disk, the Qfilesystemwatcher will stop monitoring once the directory is removed from the disk.

Note: The behavior of monitoring files and directories for modification consumes system resources. This means that your process simultaneously monitors the limit of the number of files. Some systems limit the number of open file descriptors by default to 256. That is, if your process tries to add more than 256 files or directories to the file system using the Addpath () and addpaths () functions will fail.

    • Briefly
    • Public functions
    • Signal
    • Example

Public functions
    • BOOL Addpath (const QString & Path)
      If the path exists, it is added to file system monitoring and is not added if the path does not exist or is already monitored.

      If the path is a directory, the content is modified or?? When deleted, the directorychanged () signal is emitted; otherwise, a filechanged () signal is emitted when the file is modified, renamed, or deleted from disk.

      Returns true if the monitor succeeds, otherwise false.

      The cause of the monitoring failure is usually dependent on the system, but it also includes reasons such as resource not present, access failure, or the total number of monitoring limits.

    • Qstringlist addpaths (const qstringlist & Paths)
      Add each path to add to file system monitoring, if the path does not exist or is already monitored, do not add it.

      The return value is a list of paths that cannot be monitored.

    • Qstringlist directories () const
      Returns a list of directory paths that are monitored.

    • Qstringlist files () const
      Returns a list of monitored file paths.

    • BOOL Removepath (const QString & Path)
      Removes the specified path from file system monitoring. Returns true if the monitoring was successfully removed.

      The reason for the deletion failure is usually system-related, but it may be because the path has been deleted.

    • Qstringlist removepaths (const qstringlist & Paths)
      Removes the specified path from file system monitoring. The return value is a list of paths that could not be successfully deleted.

Signal
    • void directorychanged (const QString & Path)
      This signal is emitted when the directory is modified (for example, when a file is added or deleted in the specified path) or deleted from the disk. Note: If there are several changes in a short period of time, there may be some changes that do not emit this signal. However, the final change in the sequence of changes will always emit this signal.

Note: This is a private signal that can be used for signal connections but cannot be emitted by the user.

    • void filechanged (const QString & Path)
      This signal is emitted when a file in the specified path is modified, renamed, or deleted from disk.

Note: This is a private signal that can be used for signal connections but cannot be emitted by the user.

Example

Below, let's implement a file/directory monitoring class.

FileSystemWatcher.h

#ifndef File_system_watcher_h#define file_system_watcher_h#include <QObject>#include <QMap>#include <QFileSystemWatcher>Class FileSystemWatcher: Publicqobject{Q_object Public:Static void Addwatchpath(QString path); PublicSlotsvoid directoryupdated(ConstQString &path);//directory update is called, path is a monitored route    voidFileupdated (ConstQString &path);is called when the file is modified, path is the monitoredPrivate:Explicit FileSystemWatcher(Qobject *parent =0);Private:StaticFileSystemWatcher *m_pinstance;//Single caseQfilesystemwatcher *m_psystemwatcher;//Qfilesystemwatcher variableQmap<qstring, qstringlist> M_currentcontentsmap;//Current content directory list for each monitor};#endif //File_system_watcher_h

FileSystemWatcher.cpp

#include <QDir>#include <QFileInfo>#include <qDebug>#include "FileSystemWatcher.h"filesystemwatcher* filesystemwatcher::m_pinstance =NULL; Filesystemwatcher::filesystemwatcher (Qobject *Parent): Qobject (Parent){}//Monitor files or directoriesvoid Filesystemwatcher::addwatchpath (QString path) {qdebug () << QString ("Add to watch:%1"). Arg (path);if(M_pinstance = =NULL) {m_pinstance =NewFileSystemWatcher (); M_pinstance->m_psystemwatcher =NewQfilesystemwatcher ();//Connect the Qfilesystemwatcher directorychanged and filechanged signals to the corresponding slotsConnect (M_pinstance->m_psystemwatcher, SIGNAL (directorychanged (QString)), M_pinstance, SLOT (directoryupdated (        (QString)));    Connect (M_pinstance->m_psystemwatcher, SIGNAL (filechanged (QString)), M_pinstance, SLOT (fileupdated (QString))); }//Add monitoring pathM_pinstance->m_psystemwatcher->addpath (path);//If the add path is a directory, save the current content listQfileinfo file (path);if(File.isdir ()) {ConstQdir DIRW (path); M_pinstance->m_currentcontentsmap[path] = dirw.entrylist (Qdir::nodotanddotdot | Qdir::alldirs |    Qdir::files, Qdir::D irsfirst); }}//As long as any monitored directory updates (add, delete, rename) are called. void FileSystemWatcher::d irectoryupdated (ConstQString &path) {qdebug () << QString ("Directory updated:%1"). Arg (path);//Compare the latest content and saved content to find out the difference (change)Qstringlist currentrylist = M_currentcontentsmap[path];ConstQdir dir (path); Qstringlist newentrylist = dir.entrylist (Qdir::nodotanddotdot | Qdir::alldirs |    Qdir::files, Qdir::D irsfirst);    qset<qstring> Newdirset = qset<qstring>::fromlist (newentrylist); qset<qstring> Currentdirset = qset<qstring>::fromlist (currentrylist);//Added a fileqset<qstring> newfiles = Newdirset-currentdirset; Qstringlist newFile = Newfiles.tolist ();//file has been removedqset<qstring> deletedfiles = Currentdirset-newdirset; Qstringlist DeleteFile = Deletedfiles.tolist ();//update current settingsM_currentcontentsmap[path] = newentrylist;if(!newfile.isempty () &&!deletefile.isempty ()) {//File/directory rename        if((newfile.count () = =1) && (deletefile.count () = =1) {Qdebug () << QString ("File Renamed from%1 to%2"). Arg (Deletefile.first ()). Arg (Newfile.first ()); }    }Else{//Add new files/directories to dir        if(!newfile.isempty ()) {Qdebug () <<"New Files/dirs added:"<< NewFile;foreach(QString file, newFile) {//processing operations for each new file ....}        }//delete files/directories from Dir        if(!deletefile.isempty ()) {Qdebug () <<"Files/dirs deleted:"<< DeleteFile;foreach(QString file, DeleteFile) {//processing operations for each deleted file ....}        }    }}//File modification when calledvoid Filesystemwatcher::fileupdated (ConstQString &path) {qfileinfo file (path);    QString strpath = File.absolutepath ();    QString strName = File.filename (); Qdebug () << QString ("The file%1 at path%2 is updated"). Arg (strName). Arg (strpath);}

The comments are very detailed, I will not be too much to explain, the following we can use.

#include "FileSystemWatcher.h"int main(intchar *argv[]){    QApplication a(argc, argv);    FileSystemWatcher::addWatchPath("E:/Test");    ....    return a.exec();}

The specified file/directory can be monitored by filesystemwatcher::addwatchpath (), and after monitoring, the update test can be done in the corresponding path.

The Qfilesystemwatcher of QT

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.