Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive function for listing all files in sub directories

Tags:

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?

like image 848
Maroun Avatar asked Oct 29 '12 20:10

Maroun


1 Answers

It uses standard c++ functionality. No need to include any third party library in code.

Only send directory path as parameter. It will revert you every files path present in that folder and its sub folder.

Further that, if you need to sort any specific type file (i.e. .txt or .jpg), pass extension, it will print all the files path which having respective extension.

#include <Windows.h>
#include<iostream>
#include<vector>
#include<string>
using namespace std;

vector<string> files;

std::string Recursive(std::string folder) {
    std::string search_path = folder + "/*.*";
    WIN32_FIND_DATA fd;
    HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd);
    std::string tmp;
    if (hFind != INVALID_HANDLE_VALUE) {
        do {
            if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
                if (!(!strcmp(fd.cFileName, ".") || !strcmp(fd.cFileName, ".."))) {
                    tmp = folder + "\\";
                    tmp = tmp + fd.cFileName;
                    Recursive(tmp);
                }
            }
            else {
                std::string FinalFilePath = folder + "\\" + fd.cFileName;
                files.push_back(FinalFilePath);
            }

        } while (::FindNextFile(hFind, &fd));
        ::FindClose(hFind);
    }
    return folder;
}

bool has_suffix(const std::string& str, const std::string& suffix) {
    return str.size() >= suffix.size() &&
        str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
}

int main(){
std::string folder = "C:\\Users\\Omkar\\Desktop\\Test";
    Recursive(folder);
    std::string t;
    const auto needle = std::string(".txt");
    while (!files.empty()) {
        t = files.back();
        if (has_suffix(t, ".mmt")) {
            cout << "FINAL PATH : " << t << endl;
            t.clear();
        }
        files.pop_back();
    }
return 0;
}
like image 154
Omkar Avatar answered Oct 28 '22 07:10

Omkar