I’ve been working on application lately that needs to recursively scan through directories and delete files that could potentially cause harm to someone’s computer. I won’t go into the specifics now, as this is a quick tip, but let me go over the algorithm really quick before we get to the code.
Basically, we use a QDirIterator to scan through all directories and files. The iterator can give us useful info. Literally, you can get a QFileInfo instance for the file/dir, which can be very useful to subsidize the code if you are just looking for something like, say, executables. We also have a QStringList of all the file types you don’t want, i.e. illegalFileTypes. We iterate over these until we find a match with one of these types. If we do, a simple boolean is flagged to destroy the file and we remove it.
Now, you could easily add a simple message box or something in a GUI application to confirm the deletion, which would be more sensible if you are scanning a small tree of files. However, if you are wanting to ask confirmation from the user on something much larger (>200-300 files), I’d modify the code so that it notifies the user in another way, or perhaps moves the files silently to another directory.
And… here’s the code! This is just a slap-together. You could easily turn this into a function and add an argument for the illegal file types if you want to re-use this code.
#include <QCoreApplication>
#include <QDirIterator>
#include <QDir>
#include <QDebug>
#include <QFileInfo>
#include <QStringList>
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QDirIterator it("C:/Users/Admin/Desktop/PatchIt Test Folder", QDirIterator::Subdirectories);
QStringList illegalFileTypes;
illegalFileTypes << ".exe" << ".dll" << ".py" << ".jar" << ".au3" << ".lua" << ".msi";
while (it.hasNext())
{
qDebug() << "Processing: " <<it.next();
bool illegalFile;
foreach (QString illegalType, illegalFileTypes)
{
if (it.fileInfo().absoluteFilePath().endsWith(illegalType, Qt::CaseInsensitive))
{
illegalFile = true;
break;
}
else
{
illegalFile = false;
}
}
if (illegalFile)
{
QDir dir;
dir.remove(it.filePath());
qDebug() << "Removed unsafe file.";
}
}
return app.exec();
}