列出子目录中的所有文件的递归函数 [英] Recursive function for listing all files in sub directories

查看:202
本文介绍了列出子目录中的所有文件的递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个函数,返回当前文件夹及其所有子文件夹中的所有文件的列表。我写了这段代码:

  #include< iostream> 
#include< dirent.h>
#include< cstring>

using namespace std;

int main(){
DIR * dir;是什么意思?
//从我的工作区
dir = opendir(。);
while(pdir = readdir(dir)){
if(/ **********此pdir是目录********** /){
/ **********应该在这里应该有呼叫********** /
cout<< pdir-> d_name<< endl;
}
}
closedir(dir);
return 0;
}



我在google中搜索它,我不知道如何: / p>


  • 检查当前 pdir 是否为目录

  • 进入目录并执行递归调用



同时我有一切,



任何提示?

解决方案

在以基本目录路径作为参数的过程中隔离该代码,因此您可以实际执行递归调用。它应该是像

  void recursive_file_list(const char * directory)
{
// .. 。
}

然后,检查 pdir 您获得的是一个目录,您有两个路由:




  • 您可以检查 pdir- > d_type == DT_DIR ;这会立即给你这个信息,但它不是可移植的(POSIX不要求存在 d_type 成员);此外,它不支持所有的文件系统,所以你可能会得到 DT_UNKNOWN 。如果你想跟随符号链接,你必须执行额外的检查,如果你得到 DT_LNK 。在这些情况下,您必须回到 lstat (见下文);

  • 您可以改为使用 lstat 以获取每个文件的信息,特别是检查 struct stat st_mode c>。


I'm trying to write a function that returns a list of all files on current folder and all of its sub folders. I wrote this code:

#include <iostream>
#include <dirent.h>
#include <cstring>

using namespace std;

int main() {
   DIR* dir; dirent* pdir;
   //From my workspace
   dir=opendir(".");     
   while (pdir=readdir(dir)) {
       if(/**********This pdir is a directory**********/) {
           /**********RECURSIVE CALL SHOULD BE HERE**********/
           cout<<pdir->d_name<<endl;
       }
   }
   closedir(dir);
   return 0;
}

I searched for it in google and I don't know how to:

  • Check if the current pdir is directory
  • Go inside the directory and perform the recursive call on it

Meanwhile I have everything on main because I still don't know what arguments the recursive function should have.

Any hints?

解决方案

Isolate that code in a procedure that takes the base directory path as a parameter, so you can actually perform the recursive call. It should be something like

void recursive_file_list(const char * directory)
{
    // ...
}

Then, to check if the pdir you obtained is a directory, you have two routes:

  • you can check if pdir->d_type==DT_DIR; this gives you this information immediately, but it's not portable (POSIX does not mandate the existence of the d_type member); also, it's not supported for all the filesystems, so you may get DT_UNKNOWN. If you want to follow symlinks, you have to perform extra checks also if you get DT_LNK. In these cases, you must fall back to lstat (see the point below);
  • you can instead portably use lstat to get information about each file, checking in particular the st_mode field of struct stat.

这篇关于列出子目录中的所有文件的递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆