c - 在 Linux 中递归计算目录的最快 C 代码(无文件)

标签 c linux recursion directory counting

下面的 C 代码将列出文件和目录的数量,并且比 linux find 命令快 4 倍。我只需要文件夹的数量,对文件数量甚至列出它们不感兴趣。有没有办法优化下面的代码并使其更加高效?

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

void listdir(char *path, size_t size) {
    DIR *dir;
    struct dirent *entry;
    size_t len = strlen(path);

    if (!(dir = opendir(path))) {
        fprintf(stderr, "path not found: %s: %s\n",
                path, strerror(errno));
        return;
    }

    puts(path);
    while ((entry = readdir(dir)) != NULL) {
        char *name = entry->d_name;
        if (entry->d_type == DT_DIR) {
            if (!strcmp(name, ".") || !strcmp(name, ".."))
                continue;
            if (len + strlen(name) + 2 > size) {
                fprintf(stderr, "path too long: %s/%s\n", path, name);
            } else {
                path[len] = '/';
                strcpy(path + len + 1, name);
                listdir(path, size);
                path[len] = '\0';
            }
        } else {
            printf("%s/%s\n", path, name);
        }

    }
    closedir(dir);
}

int main( int argc, char *argv[] ) {

   if( argc == 2 ) {
      printf("Path:  %s\n", argv[1]);
   }
   else if( argc > 2 ) {
      printf("Too many arguments supplied.\n");
   }
   else {
      printf("One argument expected.\n");
      return 0;
   }
    char path[1024];
    memcpy (path, argv[1],1024);
    listdir(path, sizeof path);
    return 0;
}

删除以下行当然不会显示文件,但不会加快执行时间:

} else {
            printf("%s/%s\n", path, name);
        }

最佳答案

如果您对打印文件名不感兴趣,只需删除 printf 语句即可。

但是请注意,代码中存在一些问题:

  • memcpy(path, argv[1], 1024); 可能会读取超出 argv[1] 指向的字符串末尾的内容,这是未定义的行为,或者无法生成正确的 C 字符串,这会导致函数 listdir 中出现未定义的行为。

您还可以避免在每次递归调用中重新计算目录名称的长度。

这是您可以尝试的修改版本:

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

long long countdirs(char *path, size_t size, size_t len) {
    DIR *dir;
    struct dirent *entry;
    long long count;

    if (!(dir = opendir(path))) {
        fprintf(stderr, "path not found: %s: %s\n",
                path, strerror(errno));
        return 0;
    }

    count = 1; // count this directory
    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_DIR) {
            char *name = entry->d_name;
            size_t len1 = strlen(name);
            if (*name == '.' && (len1 == 1 || (len1 == 2 && name[1] == '.')))
                continue;
            if (len + len1 + 2 > size) {
                count++;
                fprintf(stderr, "path too long: %s/%s\n", path, name);
            } else {
                path[len] = '/';
                memcpy(path + len + 1, name, len1 + 1);
                count += countdirs(path, size, len + 1 + len1);
                path[len] = '\0';
            }
        }
    }
    closedir(dir);
    return count;
}

int main(int argc, char *argv[]) {
    char buf[4096];
    char *path;
    size_t len;

    if (argc != 2) {
        fprintf(stderr, "one argument expected.\n");
        return 1;
    }
    path = argv[1];
    len = strlen(path);
    if (len >= sizeof(buf)) {
        fprintf(stderr, "path too long: %s\n", path);
        return 1;
    }   
    memcpy(buf, path, len + 1);
    printf("%s: %lld directories\n", path, countdirs(buf, sizeof buf, len));
    return 0;
}

进一步说明:

关于c - 在 Linux 中递归计算目录的最快 C 代码(无文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56811153/

相关文章:

c - C 函数的平均执行时间不稳定

c - 套接字未打开?

linux - 关闭后如何制作 LESS 'remember' 搜索模式?

c - 使用 read(..) 从 stdin 读取并计算出缓冲区的大小

linux - Beagleboard Angstrom Linux,Image Capture Script 流媒体替代品

linux - linux下如何获取进程的总内存使用量和执行时间?

json - chalice /JSON : recursive data structre for JSON#registerObjectMarshaller

c# - EF 递归层次结构

recursion - LISP-- 递归回文

c++ - 这个 rsAssert 宏的含义是什么?