【问题标题】:Most fastest C code to count recursively directories in Linux ( without files )在 Linux 中递归计算目录的最快的 C 代码(无文件)
【发布时间】:2019-11-10 15:54:48
【问题描述】:

以下 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);
        }

【问题讨论】:

  • 使用strncpy 而不是memcpy。您的代码具有越界访问权限。
  • 使用strlen(path) 而不是sizeof path。同样,可能的越界访问。
  • 使用PATH_MAX 而不是1024。最好利用你所拥有的。
  • opendir 错误不一定意味着“找不到路径”。 “找不到路径:/foo:权限被拒绝”形式的错误消息不如更简单的“/ foo:权限被拒绝”有用(并且可能令人困惑)。不要试图猜测。删除“找不到路径”
  • 对此毫无疑问。 PATH_MAX 大小和一个简单的strcpy(在检查strlen 之后)就足够了。 (但如果您检查strlen,则无需再次扫描字符串结尾,只需size_t plen = strlen (argv[1]); if (plen &lt; PATH_MAX - 1) memcpy (path, argv[1], plen + 1))

标签: c linux recursion directory counting


【解决方案1】:

如果您对打印文件名不感兴趣,只需删除 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;
}

补充说明:

【讨论】:

  • 非常感谢您的反馈和输出,关于性能-您的代码执行时间与上述相同。
  • 为什么要乱用路径呢?只需使用openat() 和fdopendir()
  • 我已经测试了 POSIX 方法,它可能更稳定,但它的执行速度比您的代码慢很多。
  • @EOF:确实,由于不使用路径,因此不需要构造它们。使用openat() 和fdopendir() 可能更安全、更高效。 (记录在这里:pubs.opengroup.org/onlinepubs/9699919799/functions/open.htmlpubs.opengroup.org/onlinepubs/9699919799/functions/…)。
  • 我已经用 fdopendir() 测试了代码,它正在执行 1s。对于相同数量的目录,速度较慢(9s。) - 690000 与 opendir() (8s) 相比
猜你喜欢
  • 2012-02-27
  • 1970-01-01
  • 2010-11-24
  • 1970-01-01
  • 2014-03-30
  • 2011-08-30
  • 1970-01-01
  • 2020-06-08
  • 2021-08-25
相关资源
最近更新 更多