簡體   English   中英

使用C ++打印所有目錄

[英]Printing all the directories using c++

該程序在根目錄下打印目錄

Directory_1
Directory_2

但我也希望能夠打印其中的目錄

Directory_1
   Directory_1_2
   Directory_1_3
Directory_2
   Directory 2_1
      Directory_2_1_1
Directory_4

我試圖遞歸地執行此操作,但是我發現很難將Directory_1作為根傳遞,以便對其進行評估。.我缺少什么?

這是我的輸出

..
.
Directory_1
Directory_2
Failed to open directory: No such file or directory

#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <sys/stat.h>

char *arg_temp;

int printDepthFirst(char *arg_tmp);

int main(int argc, char *argv[]) {

   if (argc != 2) {
      fprintf(stderr, "Usage: %s directory_name\n", argv[0]);
      return 1; 
   }  


  arg_temp = argv[1]; 

  printDepthFirst(arg_temp);

}

int printDepthFirst(char *arg_tmp)
{

   struct dirent *direntp;
   DIR *dirp;

   if ((dirp = opendir(arg_tmp)) == NULL) {
      perror ("Failed to open directory");
      return 1;
   }  


   while ((direntp = readdir(dirp)) != NULL)
  {
   printf("%s\n", direntp->d_name);
   arg_tmp = direntp->d_name;
  }    
   printDepthFirst(arg_tmp);

  while ((closedir(dirp) == -1) && (errno == EINTR)) ;
     return 0;

}

現在,我知道有些人在問一些問題時感到惱火,他們認為我希望他們對此進行編碼,如果您可以從理論上告訴我我需要做的事情,則無需這樣做。修復,您可以發布它,我會很感激..如果沒有,..我也很想聽聽需要用言語完成的事情..

謝謝

好吧,這應該有所幫助:

#define _XOPEN_SOURCE 500
#include <ftw.h>
#include <stdio.h>

static int display_info(const char *fpath, const struct stat *sb,
             int tflag, struct FTW *ftwbuf)
{
    switch(tflag)
    {
        case FTW_D:
        case FTW_DP: puts(fpath); break;
    }
    return 0; /* To tell nftw() to continue */
}

int main(int argc, char *argv[])
{
    if (argc != 2) {
        fprintf(stderr, "Usage: %s directory_name\n", argv[0]);
        return 1; 
    }  

    int flags = FTW_DEPTH | FTW_MOUNT | FTW_PHYS;

    if (nftw(argv[1], display_info, 20, flags) == -1)
    {
        perror("nftw");
        return 255;
    }

    return 0;
}

看一下struct dirent包含哪些字段。

字符串dirent :: d_name是目錄的名稱,而不是完整路徑。 因此,如果目錄“ C:\\ Alpha”包含目錄“ C:\\ Alpha \\ Beta”,則d_name僅包含“ Beta”,而不包含“ C:\\ Alpha \\ Beta”。 您必須自己匯編完整路徑-將斜杠/反斜杠附加到arg_tmp ,然后附加新的目錄名稱,如下所示:

while ((direntp = readdir (dirp)) != NULL)
{
   char *dirname = direntp->d_name;

   // Only work with directories and avoid recursion on "." and "..":
   if (direntp->d_type != DT_DIR || !strcmp (dirname, ".") || !strcmp (dirname, "..")) continue;

   // Assemble full directory path:
   char current [strlen (arg_tmp) + 2 + strlen (dirname)];
   strcpy (current, arg_tmp);
   strcat (current, "\\"); // Replace "\\" with "/" on *nix systems
   strcat (current, dirname);

   // Show it and continue:
   printf ("%s\n", current);
   printDepthFirst (current);
}

另外,您應該在循環內而不是外部遞歸調用。

printDepthFirst內部的while循環中,您可能需要類似以下內容:

if(direntp->d_type == DT_DIR)
    printDepthFirst(directp->d_name);

您可能也需要擔心..目錄。

另外,我發現boost :: filesystem可以很好地工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM