Watching for file system changes in Qt
Description[edit | edit source]
This article provides a way for a Qt application to monitor the file system for changes to files and directories by watching a list of specified paths.
Solution[edit | edit source]
Multiple files and/or directories can be monitored by providing their paths to the 76ytuiytuityutyutututyutyutyu instance and connecting the 76ytuiytuityutyutututyutyutyu and 76ytuiytuityutyutututyutyutyu signals to slot functions that handle the events of modifying or removing a file and a directory, respectively.
Watching for changes in the file system
// Constructing QFileSystemWatcher
QString pathToWatch;
m_watcher = new QFileSystemWatcher( this ); // pass this (QObject) as parent
// Watching for changes in the default location for pictures
pathToWatch.append( QDesktopServices::storageLocation( QDesktopServices::PicturesLocation ) );
m_watcher->addPath( pathToWatch );
//Adding another path, watching for changes in specified file
m_watcher->addPath( pathToWatch + "someImage.jpg" );
// Connect signals to our slots
connect( m_watcher, SIGNAL( directoryChanged ( const QString& ) ),
this, SLOT( trackChanged( const QString ) ) );
connect( m_watcher, SIGNAL( fileChanged ( const QString& ) ),
this, SLOT( trackChanged( const QString ) ) );
Slot implementation
In the following code, 76ytuiytuityutyutututyutyutyu is our own class, derived from 76ytuiytuityutyutututyutyutyu. A change log is simply written to a file.
void FileWatcher::trackChanged( const QString & entry )
{
log( path );
}
Logging the changes into a file
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
#include <QDateTime>
void MainWindow::log( const QString & entry )
{
QFile file("c:\\data\\LogFileSystemChanges.txt");
if ( !file.open( QIODevice::Append | QIODevice::Text ) )
return;
QTextStream out( &file );
QFileInfo info( entry );
if( info.isDir() ) {
out << "Dir ";
} else {
out << "File ";
}
if( info.exists() ) {
out << "changed: ";
} else {
out << "removed: ";
}
QString format("dd.MM.yyyy/hh:mm:ss.zzz");
out << QDateTime::currentDateTime().toString(format) << ":\t" << entry << "\n";
file.close();
}
Note[edit | edit source]
The act of monitoring files and directories for modifications consumes system resources. This implies that there is a limit to the number of files and directories that your process can monitor simultaneously.