Getting all files in a specified folder using Boost.
Also check out how to get files of a specific type, and sorted results here!
#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
//returns a list of all the files in a given folder.
std::vector<boost::filesystem::directory_entry> GetAllFilesInFolder(boost::filesystem::path folderPath)
{
try
{
if (exists(folderPath)) // does p actually exist?
{
std::vector<boost::filesystem::directory_entry> files;
if (is_regular_file(folderPath)) // is p a regular file?
cout << folderPath << " size is " << file_size(folderPath) << '\n';
else if (is_directory(folderPath)) // is p a directory?
{
cout << folderPath << " is a directory containing:\n";
/*
copy(boost::filesystem::directory_iterator(folderPath), boost::filesystem::directory_iterator(), // directory_iterator::value_type
ostream_iterator<boost::filesystem::directory_entry>(cout, "\n")); // is directory_entry, which is
// converted to a path by the
// path stream inserter
*/
for (auto& entry : boost::make_iterator_range(boost::filesystem::directory_iterator(folderPath), {}))
{
std::cout << entry << "\n";
files.push_back(entry);
}
return files;
}
}
else
{
cout << folderPath << " does not exist\n";
}
}
catch (const boost::filesystem::filesystem_error& ex)
{
cout << ex.what() << '\n';
}
}
Usage:
vector<boost::filesystem::directory_entry> files = GetAllFilesInFolder(folder);