このコードがコンパイルされる保証はなく、実際には Linux と BSD とのみ互換性があります:
#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);
 readdir を参照 .
サブディレクトリも含めたい場合は、コードの一部で使用しているこの関数を使用できます。エラー チェックを追加し、異なるディレクトリ セパレータをサポートするように変更する必要があります。
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;
}