Recursive function for listing all files in sub directories
c++
Solution
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`.
Problem
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?