(C++) GetCppFilesInFolder

February 24, 2017 · View on GitHub

 

 

 

 

 

(C++) GetCppFilesInFolder

 

GetCppFilesInFolder is a file I/O code snippet to obtain all C++ filenames in a folder.

 

 


#include <iostream> #include <string> #include <vector> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/regex.hpp> //From http://www.richelbilderbeek.nl/CppGetFilesInFolder.htm const std::vector<std::string> GetFilesInFolder(const std::string& folder) {   std::vector<std::string> v;   const boost::filesystem::path my_folder     = boost::filesystem::system_complete(         boost::filesystem::path(folder));   if (!boost::filesystem::is_directory(my_folder)) return v;   const boost::filesystem::directory_iterator j;   for ( boost::filesystem::directory_iterator i(my_folder);         i != j;         ++i)   {     if ( boost::filesystem::is_regular_file( i->status() ) )     {       const std::string filename = i->path().filename();       //const std::string full_filename = folder + "/" + filename;       v.push_back(filename);     }   }   return v; } //From http://www.richelbilderbeek.nl/CppGetCppFilesInFolder.htm const std::vector<std::string> GetCppFilesInFolder(const std::string& folder) {   //Get all filenames   const std::vector<std::string> v = GetFilesInFolder(folder);   //Create the regex for a correct C++ filename   const boost::regex cpp_file_regex(".*\\.(h|hpp|c|cpp)\\z");   //Create the resulting std::vector   std::vector<std::string> w;   //Copy all filenames matching the regex in the resulting std::vector   BOOST_FOREACH(const std::string& s, v)   {     if (boost::regex_match(s,cpp_file_regex)) w.push_back(s);   }   return w; } //Copy_if was dropped from the standard library by accident. template<typename In, typename Out, typename Pred> Out Copy_if(In first, In last, Out res, Pred Pr) {   while (first != last)   {     if (Pr(*first))       *res++ = *first;     ++first;   }   return res; } //From http://www.richelbilderbeek.nl/CppGetPath.htm const std::string GetPath(const std::string& filename) {   return boost::filesystem::path(filename).parent_path().string(); } //From http://www.richelbilderbeek.nl/CppGetCurrentFolder.htm const std::string GetCurrentFolder(const std::string& s) {   return GetPath(s); } int main(int /* argc */, char* argv[]) {   const std::vector<std::string> cpp_filenames     = GetCppFilesInFolder(GetCurrentFolder(argv[0]));   //Display all C++ files   std::copy(     cpp_filenames.begin(),     cpp_filenames.end(),     std::ostream_iterator<std::string>(std::cout,"\n"));   //Display the number of C++ files   std::cout << "Number of C++ files: " << cpp_filenames.size() << '\n'; }