PDA

View Full Version : Count files of a directory



radu_d
22nd October 2007, 19:50
I want to count the number of files from a directory and all its subdirectories recursively. My code is:



int DocumentsManager::CountFiles(QString path)
{
int sum = 0;
QDir dir(path);
dir.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot);
QFileInfoList lst = dir.entryInfoList();
for(int i = 0; i < lst.size(); i++)
{
sum = sum + CountFiles(lst.at(i).canonicalPath());
}
dir.setFilter(QDir::Files);
return dir.entryInfoList().size() + sum;
}


The problem is that sometimes I got the following error:
ASSERT: i>=0 && i < size()

Do you have any idea why? Thank you.

marcel
22nd October 2007, 20:04
What happens if "path" points to a file? I don't know if you can construct a QDir from that. I think you should revise your function and not call it for files, only for sub dirs.

radu_d
22nd October 2007, 20:41
It does not contains files because the filter returns only directory excluding . and .. The Problem is that it crashes only if i add My Documents folder. And i cannot debug that error :(

marcel
22nd October 2007, 20:53
Do you have permissions in that folder and all sub folders?

radu_d
22nd October 2007, 20:57
I didn't think of that .. but my user is admin ... so i should have permissions.

wysota
22nd October 2007, 21:21
I'd do:


int countFiles(const QString &path, bool countDirs=false){
QFileInfo finfo(path);
if(!finfo.exists() || !finfo.isDir())
return 0;
int res = 0;
QStringList slist = finfo.absoluteDir().entryList(QDir::Dirs|QDir::NoS ymLinks|QDir::NoDotAndDotDot);
foreach(QString path, slist){
QFileInfo childinfo(path);
if(childInfo.isDir()){
if(countDirs)
res++;
res+=countFiles(path, countDirs);
} else
res++;
}
return res;
}

dropal
27th March 2012, 04:17
int uiPrincipal::CountFiles(QString path)
{
int suma = 0;
QDir dir(path);
dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
if(!dir.exists()) {
return 1;
}
QFileInfoList sList = dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);

foreach(QFileInfo ruta, sList){
if(ruta.isDir()){
suma += CountFiles(ruta.path() + "/" + ruta.completeBaseName()+"/");
}
suma++;
}
return suma;
}