简体   繁体   English

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

[英]search and print all the files and subfolders of a directory

I have to write a C program that takes a directory as an argument, recursively prints a tree with all the files and subdirectories. 我必须编写一个将目录作为参数的C程序,以递归方式打印包含所有文件和子目录的树。 I do not know how to do this, can you help me? 我不知道该怎么做,您能帮我吗? Thanks a lot. 非常感谢。

In pure standard C, you cannot do that, since the C11 standard n1570 does not mention directories . 在纯标准C中,您不能这样做,因为C11标准n1570没有提到directory

You need some operating system specific things. 您需要一些特定于操作系统的东西。 On Linux, look into nftw(3) . 在Linux上,查看nftw(3) It uses lower level stuff like opendir(3) , readdir(3) , closedir , stat(2) that you might use directly. 它使用较低级别的东西,例如opendir(3)readdir(3)closedirstat(2) ,您可以直接使用它们。

On Windows, the API to handle directories is very different. 在Windows中,处理目录的API 非常不同的。

Some frameworks like Poco , Boost , Qt , ... try to define some common abstraction on directories working on several OSes. 诸如PocoBoostQt ,...之类的一些框架试图在可用于多种操作系统的目录上定义一些通用的抽象。 But the precise notion of directory and file is different on Windows and on Unix or Linux. 但是目录和文件的精确概念在Windows以及Unix或Linux上是不同的。 See also this . 另请参见

opendir(),readdir()and closedir() based implementations almost never handle the cases where directories or files are moved, renamed, or deleted during the tree traversal. 基于opendir(),readdir()和closedir()的实现几乎永远不会处理在遍历树期间移动,重命名或删除目录或文件的情况。 nftw() should handle them correctly nftw()应该正确处理它们

For file tree walk there are two functions. 对于文件树遍历,有两个功能。 ftw() and nftw(). ftw()和nftw()。 ftw() walks through the directory tree that is located under the directory dirpath, and calls fn() once for each entry in the tree. ftw()遍历位于目录dirpath下的目录树,并为树中的每个条目调用一次fn()。 By default, directories are handled before the files and sub-directories they contain (preorder traversal). 默认情况下,在处理目录和文件和子目录之前会对其进行处理(遍历)。

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

The function nftw() is the same as ftw(), except that it has one additional argument, flags, and calls fn() with one more argument, ftwbuf. 函数nftw()与ftw()相同,不同之处在于它具有一个附加的参数flags,并使用另一个参数ftwbuf调用fn()。 This flags argument is formed by ORing zero or more of the following flags: 该标志参数是通过对零个或多个以下标志进行“或”运算形成的:

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

These functions return 0 on success, and -1 if an error occurs. 这些函数成功返回0,如果发生错误则返回-1。

The following program traverses the directory tree under the path named in its first command-line argument, or under the current directory if no argument is supplied. 以下程序在其第一个命令行参数中命名的路径下遍历目录树,或者在没有提供参数的情况下遍历当前目录下的目录树。 It displays various information about each file. 它显示有关每个文件的各种信息。

   #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);
  }

Basile is right. 巴西利说得对。 It depends on your operating system. 这取决于您的操作系统。 There are some programs written in order to print directories/files other than ntfw , called as walking directories in POSIX. 为了打印除ntfw以外的目录/文件,编写了一些程序,在POSIX中称为walking directories For example, 例如,

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

void listdir(const char *name, int indent)
{
    DIR *dir;
    struct dirent *entry;

    if (!(dir = opendir(name)))
        return;

    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_DIR) {
            char path[1024];
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
                continue;
            snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
            printf("%*s[%s]\n", indent, "", entry->d_name);
            listdir(path, indent + 2);
        } else {
            printf("%*s- %s\n", indent, "", entry->d_name);
        }
    }
    closedir(dir);
}

int main(void) {
    listdir(".", 0);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM