Counting the number of files in a directory using C

c, file, linux

Solution

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);

Problem

How can I count the number of files in a directory using C on linux platform.

Original source