gpt4 book ai didi

c - 搜索并打印目录的所有文件和子文件夹

转载 作者:太空宇宙 更新时间:2023-11-04 05:23:11 25 4
gpt4 key购买 nike

我必须编写一个 C 程序,它将一个目录作为参数,递归地打印一个包含所有文件和子目录的树。我不知道该怎么做,你能帮我吗?非常感谢。

最佳答案

基于 opendir()、readdir() 和 closedir() 的实现几乎从不处理在树遍历期间移动、重命名或删除目录或文件的情况。 nftw() 应该正确处理它们

对于文件树遍历,有两个函数。 ftw() 和 nftw()。ftw() 遍历位于目录 dirpath 下的目录树,并为树中的每个条目调用一次 fn()。默认情况下,目录在它们包含的文件和子目录之前被处理(前序遍历)。

*int ftw(const char *dirpath,int (*fn) (const char *fpath, const struct stat sb,int typeflag),int nopenfd);

函数 nftw() 与 ftw() 相同,只是它多了一个参数 flags,并且调用 fn() 时还多了一个参数 ftwbuf。此标志参数由以下标志中的零个或多个 OR 组成:

int nftw(const char *dirpath,int (*fn) (const char *fpath, const struct stat *sb,int typeflag, struct FTW *ftwbuf), int nopenfd, int flags);

这些函数在成功时返回 0,如果发生错误则返回 -1。

以下程序遍历其第一个命令行参数中命名的路径下的目录树,如果未提供参数,则遍历当前目录下的目录树。它显示有关每个文件的各种信息。

   #define _XOPEN_SOURCE 500
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

static int display_info(const char *fpath, const struct stat *sb,
int tflag,struct FTW *ftwbuf)
{
printf("%-3s %2d %7jd %-40s %d %s\n",
(tflag == FTW_D) ? "d" : (tflag == FTW_DNR) ? "dnr" :
(tflag == FTW_DP) ? "dp" : (tflag == FTW_F) ? "f" :
(tflag == FTW_NS) ? "ns" : (tflag == FTW_SL) ? "sl" :
(tflag == FTW_SLN) ? "sln" : "???",
ftwbuf->level, (intmax_t) sb->st_size,
fpath, ftwbuf->base, fpath + ftwbuf->base);
return 0; /* To tell nftw() to continue */
}

int main(int argc, char *argv[])
{
int flags = 0;

if (nftw((argc < 2) ? "." : argv[1], display_info, 20, flags)
== -1) {
perror("nftw");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}

关于c - 搜索并打印目录的所有文件和子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50290155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com