How can I count the number of files in a directory using C on linux platform.
+11
A:
No guarantee that this code compiles, and it's really only compatible with Linux and the BSDs:
#include <dirent.h>
...
int file_count = 0;
DIR * dirp;
struct dirent * entry;
dirp = opendir("path"); /* There should be error handling after this */
while ((entry = readdir(dirp)) != NULL) {
if (entry->d_type == DT_REG) { /* If the entry is a regular file */
file_count++;
}
}
closedir(dirp);
Michiel Buddingh'
2009-07-13 19:02:53
If you want to process files in subdirectories, you can recurse when you encounter a directory entry. Make sure to exclude "." and ".." if you do this.
Jay Conrod
2009-07-13 19:07:27
Good job on catching the dirent include.
Michiel Buddingh'
2009-07-13 19:09:44
Aren't `opendir`, `readdir` and `closedir` POSIX.1-2001?
dreamlax
2009-08-27 06:26:48
Yes, they are POSIX functions.
penguru
2009-08-27 13:04:05
POSIX specifies only d_ino and d_name as members of the dirent-structure. This code tests for d_type, which is platform-specific.
Michiel Buddingh'
2009-08-27 19:50:02
A:
How can I count the number of files in a directory using C on Windows Platform?
Sunayana
2010-06-29 11:23:40