I am developing an Application for MAC OS X. In which I have to find files in folder. Problem is that I want to give comfort, to user, to search a file by entering a QString
. This QString may be the exact name of file or a text contain in the file name.Suppose the file name is "mysamplefile.txt"
. So if user enter either 'my'
; 'mysample'
; 'samplefile'
; 'mysamplefile'
or 'mysamplefile.txt'
. In all cases I want to get the QFileInfo
for that file. I also give checkbox option 'Match Case'
or 'Ignore case'
to the user to get fileinfo
. I have a QStringList
for the strings
that user want to search and I also have a QStringList
of the locations selected by the user. So I want to search each string name(from QStringList strSearchFileName
) in every Path(QStringList searchingdirectorylist
). And I want to make a final QFileInfoList
for all files after the searching process.
void MainWindowWipe::onSearchingProcess(QStringList strSearchFileName, QStringList searchingdirectorylist)
{
for(int i=0; i<strSearchFileName.size();i++)
{
for(j=0; j<searchingdirectorylist.size();j++)
{
QDir dir(searchingdirectorylist[j]);
dir.setNameFilters(QStringList(strSearchFileName[i]));
dir.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
QFileInfoList fileList = dir.entryInfoList();
for (int k=0; k<fileList.count(); k++)
{
QString temp = "";
temp = fileList[k].absoluteFilePath();
}
dir.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
QStringList dirList = dir.entryList();
QStringList newList;
for (int l=0; l<dirList.size(); ++l)
{
QString newPath = QString("%1/%2").arg(dir.absolutePath()).arg(dirList.at(i));
newList<<newPath;
onSearchingProcess(strSearchFileName,newList);
}
}
}
}
This function is not working for me this work only when if I search only one file with exact name. But I want to search multiple files with not exact name.
You need to iterate through all the files and folders using a recursive function (or use the iterator). On each iteration you can use the QString::contains()
to find out if the file's name contains the target string. Save each matching file name in a list.
#include <QCoreApplication>
#include <QDebug>
#include <QDirIterator>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString targetStr = "init"; // What we search for
QFileInfoList hitList; // Container for matches
QString directory = "D:/python/"; // Where to search
QDirIterator it(directory, QDirIterator::Subdirectories);
// Iterate through the directory using the QDirIterator
while (it.hasNext()) {
QString filename = it.next();
QFileInfo file(filename);
if (file.isDir()) { // Check if it's a dir
continue;
}
// If the filename contains target string - put it in the hitlist
if (file.fileName().contains(targetStr, Qt::CaseInsensitive)) {
hitList.append(file);
}
}
foreach (QFileInfo hit, hitList) {
qDebug() << hit.absoluteFilePath();
}
return a.exec();
}