簡體   English   中英

搜索並打印目錄的所有文件和子文件夾

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

我必須編寫一個將目錄作為參數的C程序,以遞歸方式打印包含所有文件和子目錄的樹。 我不知道該怎么做,您能幫我嗎? 非常感謝。

在純標准C中,您不能這樣做,因為C11標准n1570沒有提到directory

您需要一些特定於操作系統的東西。 在Linux上,查看nftw(3) 它使用較低級別的東西,例如opendir(3)readdir(3)closedirstat(2) ,您可以直接使用它們。

在Windows中,處理目錄的API 非常不同的。

諸如PocoBoostQt ,...之類的一些框架試圖在可用於多種操作系統的目錄上定義一些通用的抽象。 但是目錄和文件的精確概念在Windows以及Unix或Linux上是不同的。 另請參見

基於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,並使用另一個參數ftwbuf調用fn()。 該標志參數是通過對零個或多個以下標志進行“或”運算形成的:

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

這些函數成功返回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);
  }

巴西利說得對。 這取決於您的操作系統。 為了打印除ntfw以外的目錄/文件,編寫了一些程序,在POSIX中稱為walking directories 例如,

#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