Valentin H
Valentin H

Reputation: 7458

Creating a hash-value of a directory in Qt

Is there any mean to determine if the directory content (including deep subdirectory structure) has changed since last access? I'm looking for a portable solution in C/C++, preferably in Qt.

P.S.: If relevant, the background of the question. In my application I have to scan recursively many directories and import some data in a database, when some conditions are true. Once the directory was imported, I mark it with a file ".imported" and ignore next times.

Now I want to mark also scanned but not imported directories. For this I'd store a file containing a directory hash. So, prior to scan I could compare the hash calculated with the last hash in file and skip scanning if they are equal.

Upvotes: 2

Views: 2040

Answers (1)

TheDarkKnight
TheDarkKnight

Reputation: 27621

There is a QFileSystemWatcher class that will notify you of changes.

If you want to create a Cryptographic Hash of a directory and its contents, this is how I do it: -

void AddToHash(const QFileInfo& fileInf, QCryptographicHash& cryptHash)
{
    QDir directory(fileInf.absoluteFilePath());
    directory.setFilter(QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Files);
    QFileInfoList fileInfoList = directory.entryInfoList();

    foreach(QFileInfo info, fileInfoList)
    {
        if(info.isDir())
        {   
            // recurse through all directories
            AddToHash(info, cryptHash);
            continue;
        }

        // add all file contents to the hash
        if(info.isFile())
        {
            QFile file(info.absoluteFilePath());
            if(!file.open(QIODevice::ReadOnly))
            {      
                // failed to open file, so skip              
                continue;
            }
            cryptHash.addData(&file);
            file.close();
        }
    }
}

// create a fileInfo from the top-level directory
QFileInfo fileInfo(filePath);
QString hash;
// Choose an arbitrary hash, say Sha1
QCryptographicHash cryptHash(QCryptographicHash::Sha1);
// add all files to the hash
AddToHash(fileInfo, cryptHash);
// get a printable version of the hash
hash = cryptHash.result().toHex();

Upvotes: 5

Related Questions