Last active
March 7, 2023 08:53
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this is kinda slow. u scan again and again depends on how much extension did u passed.