How can I count the number of files in a directory using C on linux platform.
If you want to include subdirectories as well, you can use this function that I'm using in some of my code. You should probably modify it to include some more error checking and support different directory separators.
int countfiles(char *path) {
DIR *dir_ptr = NULL;
struct dirent *direntp;
char *npath;
if (!path) return 0;
if( (dir_ptr = opendir(path)) == NULL ) return 0;
int count=0;
while( (direntp = readdir(dir_ptr)))
{
if (strcmp(direntp->d_name,".")==0 ||
strcmp(direntp->d_name,"..")==0) continue;
switch (direntp->d_type) {
case DT_REG:
++count;
break;
case DT_DIR:
npath=malloc(strlen(path)+strlen(direntp->d_name)+2);
sprintf(npath,"%s/%s",path, direntp->d_name);
count += countfiles(npath);
free(npath);
break;
}
}
closedir(dir_ptr);
return count;
}