Подсчет количества файлов в каталоге с помощью C - PullRequest
15 голосов
/ 13 июля 2009

Как подсчитать количество файлов в каталоге, используя C на платформе linux.

Ответы [ 3 ]

36 голосов
/ 13 июля 2009

Нет гарантии, что этот код компилируется, и он действительно совместим только с 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);
6 голосов
/ 13 июля 2009

См. readdir.

0 голосов
/ 03 января 2018

Если вас не волнует текущий каталог . и родительский каталог .., подобные этим:

drwxr-xr-x  3 michi michi      4096 Dec 21 15:54 .
drwx------ 30 michi michi     12288 Jan  3 10:23 ..

Вы можете сделать что-то вроде этого:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

int main (void){
    size_t count = 0;
    struct dirent *res;
    struct stat sb;
    const char *path = "/home/michi/";

    if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)){
        DIR *folder = opendir ( path );

        if (access ( path, F_OK ) != -1 ){
            if ( folder ){
                while ( ( res = readdir ( folder ) ) ){
                    if ( strcmp( res->d_name, "." ) && strcmp( res->d_name, ".." ) ){
                        printf("%zu) - %s\n", count + 1, res->d_name);
                        count++;
                    }
                }

                closedir ( folder );
            }else{
                perror ( "Could not open the directory" );
                exit( EXIT_FAILURE);
            }
        }

    }else{
        printf("The %s it cannot be opened or is not a directory\n", path);
        exit( EXIT_FAILURE);
    }

    printf( "\n\tFound %zu Files\n", count );
}

Выход:

1) - .gnome2
2) - .linuxmint
3) - .xsession-errors
4) - .nano
5) - .kde
6) - .xsession-errors.old
7) - .gnome2_private
8) - Public
9) - .gconf
10) - .bashrc
11) - .macromedia
12) - .thunderbird
13) - Pictures
14) - .profile
15) - .cinnamon
16) - .pki
17) - Compile
18) - Desktop
19) - .Private
20) - .cache
21) - .Xauthority
22) - .ICEauthority
23) - VirtualBox VMs
24) - .bash_history
25) - .mozilla
26) - .local
27) - .config
28) - .codeblocks
29) - Documents
30) - .bash_logout
31) - Videos
32) - Templates
33) - Downloads
34) - .adobe
35) - .gphoto
36) - Music
37) - .dbus
38) - .ecryptfs
39) - .sudo_as_admin_successful
40) - .gnome

    Found 40 Files
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...