Joey Carson
Joey Carson

Reputation: 3113

What is the implementation of QDir::count()

All over the internet it seems the accepted way of getting a directory's child count is to loop through its entries manually and count them. This seems far too tedious and generally there are other frameworks and API's that offer a convenience function to get child counts, one of them being QDir::count().

Is there a POSIX API that returns the number of entries in a directory efficiently? If so, I would imagine that this is the implementation of QDir::count(). If not, then perhaps it's done the way so many people are doing it, looping through the entries and counting them if they're appropriate.

Upvotes: 2

Views: 175

Answers (1)

Michael Burr
Michael Burr

Reputation: 340218

Internally, QDir iterates over the directory reading the entries into a list. QDir::count() returns the number of entries in that list (count() will populate the list if that hasn't happened yet).

See qtbase/src/corelib/io/qdir.cpp for the implementation of

  • QDir::count():

    uint QDir::count() const
    {
        const QDirPrivate* d = d_ptr.constData();
        d->initFileLists(*this);
        return d->files.count();
    }
    
  • QDirPrivate::initFileLists():

    inline void QDirPrivate::initFileLists(const QDir &dir) const
    {
        if (!fileListsInitialized) {
            QFileInfoList l;
            QDirIterator it(dir);
            while (it.hasNext()) {
                it.next();
                l.append(it.fileInfo());
            }
            sortFileList(sort, l, &files, &fileInfos);
            fileListsInitialized = true;
        }
    }
    

Upvotes: 4

Related Questions