Skip to content

Instantly share code, notes, and snippets.

@FlynnOConnell
Last active December 17, 2022 21:51
Show Gist options
  • Save FlynnOConnell/7206d8f0c952a4a8dd1f18328b62886e to your computer and use it in GitHub Desktop.
Save FlynnOConnell/7206d8f0c952a4a8dd1f18328b62886e to your computer and use it in GitHub Desktop.
Recursively gets files from a certain directory.
/// <summary>Recursively gets files from a certain directory.</summary>
/// <remarks>These files can be filtered by if they end with certain file extensions.</remarks>
/// <param name="directory">Path to the directory to get the files from</param>
/// <param name="extensions">List of file extensions to filter by</param>
/// <param name="depth">Current folder depth</param>
/// <param name="maxDepth">Max folder depth to iterate through</param>
/// <returns>The files from a certain directory</returns>
std::vector<std::filesystem::path> PremierSuite::IterateDirectory(const std::filesystem::path& directory,
const std::vector<std::string>& extensions,
const int depth, const int maxDepth) {
if (depth > maxDepth) {
return std::vector<std::filesystem::path>();
}
std::vector<std::filesystem::path> files;
for (const std::filesystem::directory_entry& file : std::filesystem::directory_iterator(directory)) {
const std::filesystem::path& filePath = file.path();
if (file.is_directory()) {
std::vector<std::filesystem::path> directoryFiles = IterateDirectory(
filePath, extensions, depth + 1, maxDepth);
// Remove if directory is empty.
if (!directoryFiles.empty()) {
files.insert(files.end(), directoryFiles.begin(), directoryFiles.end());
}
}
else if (HasExtension(filePath.extension().string(), extensions)) {
files.push_back(filePath);
}
}
return files;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment