Count all files in directory and subdirectories



  • Is there a Qt function that counts all files in a directory and all subdirectories? I need to know the total amount of files so that I can create a progressbar as another function processes each file.

    @
    dir.count();
    @
    This only gives me the total amount of files in current directory.



  • I assume you are using QDir class for variable dir above. Anyway this sounds like a recursive problem. This is possile as long as you guarantee that there are no links. The following is an implementation. Modify it if appropriate.

    @
    int countFilesAndDirRecursive(QString dirName){
    QDir dir(dirName);
    int count = 0;
    QStringList fileNameList = dir.entryList();
    for(QStringList::Iterator iter = fileNameList.begin(); iter != fileNameList.end(); iter++){
    // Test if *iter is directory.
    bool isDir = dir.cd(*iter);
    if(isDir){
    // It is a directory.
    count += countFilesAndDirRecursive(*iter);

       // Change back to parent.
       dir.cdUp();
       continue;
    }
    

    }
    return count;
    }@

    IMPORTANT NOTE: This will guarantee to stop if and only if there are no links(LINUX)/shortcuts(WINDOWS) in your file system. Other than that it should work. There might be some syntax errors since this is typed in my small travel computer.



  • Thanks.
    So I will have to implement counting recursively myself. Will have to put that function on a different thread to keep the GUI responsive.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.