【问题标题】:Recursively list directories in C递归列出C中的目录
【发布时间】:2013-07-01 11:50:20
【问题描述】:

我正在寻找一个代码,该代码将递归列出 C 编程中参数给出的目录的所有目录和文件,我找到了一个有趣的代码(如下),但我不了解 snprintf 函数,特别是“/”, 我更喜欢使用 strcat 或其他系统函数来覆盖 sprintf 函数,但我不明白如何,因为我不明白 snprintf 在这里做什么。 代码如下:

int is_directory_we_want_to_list(const char *parent, char *name) {
    struct stat st_buf;
    if (!strcmp(".", name) || !strcmp("..", name))
        return 0;

    char *path = alloca(strlen(name) + strlen(parent) + 2);
    sprintf(path, "%s/%s", parent, name);
    stat(path, &st_buf);
    return S_ISDIR(st_buf.st_mode);
}

int list(const char *name) {
    DIR *dir = opendir(name);
    struct dirent *ent;

    while (ent = readdir(dir)) {
        char *entry_name = ent->d_name;
        printf("%s\n", entry_name);

        if (is_directory_we_want_to_list(name, entry_name)) {
            // You can consider using alloca instead.
            char *next = malloc(strlen(name) + strlen(entry_name) + 2);
            sprintf(next, "%s/%s", name, entry_name);
            list(next);
            free(next);
        }
    }

    closedir(dir);
}

来自How to recursively list directories in C on LINUX

好的,我的程序正在运行,但现在我想将打印的所有文件和目录保存到一个文件中,就像我运行我的程序 ./a.out 一样。 > 缓冲区,其中缓冲区包含程序应在 shell 上打印的内容

【问题讨论】:

  • 呃... snprintf 叫什么?代码 sn-p 中没有。如果您不了解它的作用,为什么不查找它的作用? cplusplus.com/reference/cstdio/snprintf
  • 您的 sprintf 到底有什么问题?它只是连接 3 个字符串 - 名称、“/”和 entry_name。
  • 我认为 sprintf 正在制造所有问题

标签: c


【解决方案1】:

线

sprintf(next, "%s/%s", name, entry_name);

可以替换为

strcpy (next, name);
strcat (next, "/");
strcat (next, entry_name);

它会做同样的事情。这对你来说清楚了吗?

【讨论】:

  • 那很快,是的,我现在好多了,谢谢,是的,它是 sprintf,对不起
  • 请注意,每次对strcat() 的调用都涉及遍历整个字符串以找到它的结尾,因此在此处调用sprintf() 会更有效。
猜你喜欢
  • 2013-08-17
  • 1970-01-01
  • 2013-10-26
  • 2012-01-16
  • 2011-06-22
  • 2010-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多