PDA

View Full Version : How to exclude a specific file extension from QDir::entryList



franco.amato
7th March 2022, 19:00
Hi community,
I know how to specify the file extensions that I would like to be considered when I call the QDir::entryList method:


QDir dir(path);
QStringList files = dir.entryList(QStringList() << "*.ext1" << "*.ext2", QDir::Files | QDir::NoDot | QDir::NoDotAndDotDot);

In this case the files having extensions ext1 and ext2 only are considered. But how to exclude a specific extension?
For example I would like to considere ALL the extensions except a specific one ( in my case *.conf )

Thx

Ginsengelf
8th March 2022, 07:27
Hi, I'm not sure if entryList() can do that. But you can simply get all files, then iterate over the stringlist and remove the matching files afterwards.

Ginsengelf

d_stranz
9th March 2022, 16:31
Something like this:



// Note that since QFileInfo::suffix() returns the extension -without- a leading ".", the code allows the
// excluded extensions list to contain either "ext" or ".ext" and will check for both.
//
// This will also include files with no extensions, so if that is not desired, check the suffix for isEmpty()
// and discard them too.
//
// Usage:
//
// QStringList noBinaryList = excludedEntryList( path, QStringList() << ".exe" << "dll", QDir::Files | QDir::NoDot | QDir::NoDotAndDotDot );

// Untested code! Might contain bugs

QStringList excludedEntryList( const QString & path, const QStringList & excludedExts, QDir::Filters filters )
{
QStringList filteredEntries;
QDir dir( path );
QFileInfoList unfilteredInfos = dir.entryInfoList( filters );
for ( QFileInfo info : unfilteredInfos )
{
QString ext = info.suffix();
if ( !excludedExts.contains( ext ) && !excludedExts.contains( "." + ext ) )
filteredEntries.push_back( info.fullPath() );
}
return filteredEntries;
}