Skip to content

Instantly share code, notes, and snippets.

@Ashwinning
Last active November 6, 2020 14:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ashwinning/3d838897c149de5580d6336168fbd9ce to your computer and use it in GitHub Desktop.
Save Ashwinning/3d838897c149de5580d6336168fbd9ce to your computer and use it in GitHub Desktop.
Getting all files of a specific type, in a specified folder using Boost. (returned in alphabetical order) #gistblog #boost #c++

Getting all files of a specific type, in a specified folder using Boost. (returned in alphabetical order)

//Accepts a path to a directory
//a file extension
//and a list
//Puts all files matching that extension in the directory into the given list.
//Sorts and returns the results
void GetFilesOfTypeInDirectory(const boost::filesystem::path &directoryPath, const string &fileExtension, std::vector<boost::filesystem::path> &list)
{
    if(!boost::filesystem::exists(directoryPath) || !boost::filesystem::is_directory(directoryPath))
    {
      std::cerr << directoryPath << "is not a directory." << std::endl;
      return;
    }

    boost::filesystem::recursive_directory_iterator it(directoryPath);
    boost::filesystem::recursive_directory_iterator endit;

    while(it != endit)
    {
        if(boost::filesystem::is_regular_file(*it) && it->path().extension() == fileExtension) list.push_back(it->path());
        ++it;
    }

    //Sort the list using our path comparing function
    std::sort(list.begin(), list.end(), PathSort);

}

bool PathSort(const boost::filesystem::path &first, const boost::filesystem::path &second)
{
    return first.filename().string() < second.filename().string();
}
@dholland4
Copy link

I do not see a license listed for your codes. Would it be possible to add one or point me to where it is so I know the restrictions on using the provided code?

Thank you!

@Ashwinning
Copy link
Author

Ashwinning commented Nov 6, 2020

I do not see a license listed for your codes. Would it be possible to add one or point me to where it is so I know the restrictions on using the provided code?

Thank you!

Hey @dholland4,

Honestly, I haven't touched C++ in 4 years, but this looks like fairly standard code.
Google search for the method name "GetFilesOfTypeInDirectory" yields only this gist as a search result, all the functions being used return results from Boost's documentation.

Seems like it depends on Boost and the standard library, but feel free to do whatever you desire to with these 9 lines of code, consider it a WTFPL license for this bit.

Have fun!

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