使用 C 计算 Linux 目录和子目录中的文件数

Count Files in directory and subdirectory in Linux using C

我正在尝试计算目录及其子目录的文件数。但是我每次都遇到段错误,我不明白为什么。

我使用了这里的代码: Counting the number of files in a directory using C

感谢帮助

#include <stdio.h>   // use input/output functions
#include <string.h>  // use string functions
#include <dirent.h>  // use directory functions

int countFilesRec(char* dirName);

// Global variable
int countFiles = 0;

/** Count files and subdirectories in given directory. */
int main(int argc, char* argv[])
{
    // Read parameters
    if (argc != 2) {
        printf("Usage: countFiles <directory>\n");
        return -1;
    }

    // Count Files
    printf(countFilesRec(argv[1]));

    return 0;
}

   
int countFilesRec(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;

                                if (strcmp(direntp->d_name,"arbeitspfad bsks.txt")==0){
                                    count=count-1;
                                    count=count+1;
                                }

                                //printf("%s\n",direntp->d_name);
                break;
            case DT_DIR:
                npath=malloc(strlen(path)+strlen(direntp->d_name)+2);
                sprintf(npath,"%s/%s",path, direntp->d_name);
                                //printf("%s\n",npath);
                count += countFilesRec(npath);
                free(npath);
                break;
        }
    }
    closedir(dir_ptr);
        //printf(count);
    return count;
}

printf 不取整数。它需要一个格式字符串和一个可变参数列表。您的问题可能可以通过更改来解决:

    // Count Files
    printf(countFilesRec(argv[1]));

   int fileCount = countFilesRec(argv[1]);
   printf("File count = %d\n", fileCount);

更改将函数的整数结果存储在变量中,然后使用合适的格式字符串打印它。