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
pdiris 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
Then, to check if the
pdiryou obtained is a directory, you have two routes:pdir->d_type==DT_DIR; this gives you this information immediately, but it’s not portable (POSIX does not mandate the existence of thed_typemember); also, it’s not supported for all the filesystems, so you may getDT_UNKNOWN. If you want to follow symlinks, you have to perform extra checks also if you getDT_LNK. In these cases, you must fall back tolstat(see the point below);lstatto get information about each file, checking in particular thest_modefield ofstruct stat.