I need to monitore a filesystem, i have a function which browse folders and files recursively and which add theirs path to my QFileSystemWatcher :

void watchFileSystem(const QDir& dir, QFileSystemWatcher& watcher)
{
    watcher.addPath(dir.absolutePath());
    QDirIterator iterator(dir.absolutePath(), QDirIterator::Subdirectories);
    while (iterator.hasNext()) {
        QString foldername = QString(iterator.fileName());
        if (foldername != "." && foldername != ".." && foldername != "")
            watcher.addPath(iterator.filePath());
        iterator.next();
        if (!iterator.fileInfo().isDir()) {
            watcher.addPath(iterator.filePath());
        }
    }
}

While running, every "watcher.addPath(iterator.filePath());" I have this error message in the console :

QFileSystemWatcher: failed to add paths: C:/.../anyfile.ext

The strangest thing is that it works anyway. When I rename/edit a file or a folder, the fileChanged and folderChanged event is triggered.

Anyone has an idea of what is happening ? I'm worried about an instability of my program, this error can't be shown for nothing.

Thanks for reading and help,

Raphael.

有帮助吗?

解决方案

The warning is shown because your loop adds files twice:

In the middle of your loop, you do iterator.next();. If that moves the iterator to a file, it will be added within the next if statement. Now your loop goes on, but still points to the same file. If the foldername is not ".", ".." or "" which is it not in case of a file, the same file is added again.

I've restructured your loop to make it work:

while (iterator.hasNext()) 
{    
    QString fileOrFolderName = QString(iterator.fileName());

    // Skip non-folders
    if (fileOrFolderName == "." || fileOrFolderName == ".." || 
        fileOrFolderName == "")
    {
        iterator.next();
        continue;
    }

    // Add the folder or file
    watcher.addPath(iterator.filePath());
    iterator.next();
}

This will add all folders and files below the directory supplied to the function.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top