I'm getting last modified file in a directory using a QFileSystemWatcher with QDir & QFileInfoList. I create a slot for directoryChanged(QString) signal in my class inherited from QFileSystemWatcher. So when ever a file is created/modified, the slot stateChanged(QString str) is getting emitted 4 times. I'm unable to understand the reason why the slot is being called 4 times.
Here's my implementation -
// cfilesystemwatcher.cpp
#include "cfilesystemwatcher.h"
#include <QDebug>
#include <QDir>
#include <QFileInfoList>
#include <QDateTime>
CFileSystemWatcher
::CFileSystemWatcher(QObject *parent
) :{
// connections
connect(this,
SIGNAL(directoryChanged
(QString)),
this,
SLOT(stateChanged
(QString)));
connect(this,
SIGNAL(fileChanged
(QString)),
this,
SLOT(stateChanged
(QString)));
}
void CFileSystemWatcher
::stateChanged(QString str
) // <<--- slot {
dir.setPath(str);
QFileInfoList list
= dir.
entryInfoList(QDir::NoDotAndDotDot |
QDir::Files,
QDir::Time);
// Here I'm getting the last modified file.
qDebug() << list.first().baseName(); // <<--- This debug is printing the name 4 times to the console for 1 modification
}
// cfilesystemwatcher.cpp
#include "cfilesystemwatcher.h"
#include <QDebug>
#include <QDir>
#include <QFileInfoList>
#include <QDateTime>
CFileSystemWatcher::CFileSystemWatcher(QObject *parent) :
QFileSystemWatcher(parent)
{
// connections
connect(this, SIGNAL(directoryChanged(QString)), this, SLOT(stateChanged(QString)));
connect(this, SIGNAL(fileChanged(QString)), this, SLOT(stateChanged(QString)));
}
void CFileSystemWatcher::stateChanged(QString str) // <<--- slot
{
QDir dir;
dir.setPath(str);
QFileInfoList list = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files, QDir::Time);
// Here I'm getting the last modified file.
qDebug() << list.first().baseName(); // <<--- This debug is printing the name 4 times to the console for 1 modification
}
To copy to clipboard, switch view to plain text mode
// main.cpp
#include <QCoreApplication>
#include "cfilesystemwatcher.h"
int main(int argc, char *argv[])
{
CFileSystemWatcher fileWatcher;
fileWatcher.addPath("/home/Rahul/Desktop/");
return a.exec();
}
// main.cpp
#include <QCoreApplication>
#include "cfilesystemwatcher.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
CFileSystemWatcher fileWatcher;
fileWatcher.addPath("/home/Rahul/Desktop/");
return a.exec();
}
To copy to clipboard, switch view to plain text mode
Now why is the slot with my qDebug() statement getting called 4 times ?
Also this is not giving the files modified inside the subs directories of the specified path. How do I make it emit signal for changes specified to a directory recursively ?
Thank you.
Bookmarks