簡體   English   中英

遞歸查找子目錄和文件

[英]Recursively find subdirectories and files

我想遞歸地檢索給定路徑中包含的所有文件,目錄和子目錄。 但是,當我的代碼到達第二級(目錄中的目錄)時,我遇到了一個問題:它沒有打開內部目錄來搜索其內容,而是引發了錯誤。 這是我所做的:

void getFile(char *path)
{

    DIR *dir;
    struct dirent *ent;
    if ((dir = opendir(path)) != NULL) {
    /* print all the files and directories within directory */
    while ((ent = readdir(dir)) != NULL) {
      if((strcmp(ent->d_name,"..") != 0) && (strcmp(ent->d_name,".") != 0)){

      printf ("%s", ent->d_name);

      if(ent->d_type == DT_DIR){

      printf("/\n");
      getFile(ent->d_name);
      }
      else{

      printf("\n");
      }
      }   // end of if condition
    }     // end of while loop
    closedir (dir);

}

使用ftw(3)庫函數以遞歸方式遍歷文件樹。 這是很標准的。

您也可以查看nftwMUSL libc代碼 這是很可讀的。

遞歸調用getFile ,僅使用您剛剛讀取的目錄名稱來調用它。 不是您需要的完整路徑。 您必須自己進行管理。


像這樣:

if(ent->d_type == DT_DIR)
{
    if ((strlen(path) + strlen(ent->d_name) + 1) > PATH_MAX)
    {
        printf("Path to long\n");
        return;
    }

    char fullpath[PATH_MAX + 1];

    strcpy(fullpath, path);
    strcat(fullpath, "/");
    strcat(fullpath, ent->d_name); // corrected

    getFile(fullpath);
}

暫無
暫無

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

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