【问题标题】:Count Files in directory and subdirectory in Linux using C使用C计算Linux中目录和子目录中的文件
【发布时间】:2021-08-25 17:06:46
【问题描述】:

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

我使用了这里的代码: 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(countFilesRec(argv[1])); 等问题。可能是“警告:传递 'printf' 的参数 1 使指针从整数而不进行强制转换 [-Wint-conversion]”

标签: c linux file ansi-c


【解决方案1】:

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

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

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

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

【讨论】: