Skip to content

Instantly share code, notes, and snippets.

@deysumitkr
Last active March 7, 2023 08:53
Show Gist options
  • Save deysumitkr/14dbb0e6a8c04d2ae9048f6f24eed9ce to your computer and use it in GitHub Desktop.
Save deysumitkr/14dbb0e6a8c04d2ae9048f6f24eed9ce to your computer and use it in GitHub Desktop.
get all files in directory - may filter by extension - may recurse - (Boost required)
// usage
std::vector<std::string> exts{".jpg", ".png"};
std::vector<std::string> files = getFilesInDir("/path/to/root/directory/", exts, true);
// --------------------------------------------------------
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>
/**
* @note If extension is empty string ("") then all files are returned
* @param Path root directory
* @param extension String or vector of strings to filter - empty string returns all files - default: ""
* @param recursive Set true to scan directories recursively - default false
* @return Vector of strings with full paths
*/
std::vector<std::string> getFilesInDir(const std::string &path, const std::string &extension="", const bool &recursive=false){
std::vector<std::string> files;
boost::filesystem::path dir(path);
if(boost::filesystem::exists(path) && boost::filesystem::is_directory(path)){
if(recursive){
boost::filesystem::recursive_directory_iterator it(path);
boost::filesystem::recursive_directory_iterator endit;
while (it != endit) {
if(boost::filesystem::is_regular_file(*it) && (extension=="")?true:it->path().extension() == extension) {
files.push_back(it->path().string());
}
++it;
}
}
else {
boost::filesystem::directory_iterator it(path);
boost::filesystem::directory_iterator endit;
while (it != endit) {
if(boost::filesystem::is_regular_file(*it) && (extension=="")?true:it->path().extension() == extension) {
files.push_back(it->path().string());
}
++it;
}
}
}
return files;
}
std::vector<std::string> getFilesInDir(const std::string &path, const std::vector<std::string> &extension, const bool &recursive=false){
if(extension.size() <=0) return getFilesInDir(path, "", recursive);
std::vector<std::string> outArray;
for (const std::string &ext: extension){
std::vector<std::string> files = getFilesInDir(path, ext, recursive);
outArray.insert(outArray.end(), files.begin(), files.end());
}
return outArray;
}
@TomieAi
Copy link

TomieAi commented Mar 7, 2023

  for (const std::string &ext: extension){
        std::vector<std::string> files = getFilesInDir(path, ext, recursive);
        outArray.insert(outArray.end(), files.begin(), files.end());
    }

this is kinda slow. u scan again and again depends on how much extension did u passed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment