Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of files with a specific extension in a given folder?

I want to get the file names of all files that have a specific extension in a given folder (and recursively, its subfolders). That is, the file name (and extension), not the full file path. This is incredibly simple in languages like Python, but I'm not familiar with the constructs for this in C++. How can it be done?

like image 777
Jim Avatar asked Jun 21 '12 14:06

Jim


People also ask

How do I search for all files with specific extensions?

For finding a specific file type, simply use the 'type:' command, followed by the file extension. For example, you can find . docx files by searching 'type: . docx'.

Which command is used to list all the files having extension txt?

locate command syntax: Similarly, you can follow the syntax of locate command for finding all files with any specific extension such as “. txt.”


1 Answers

#define BOOST_FILESYSTEM_VERSION 3 #define BOOST_FILESYSTEM_NO_DEPRECATED  #include <boost/filesystem.hpp>  namespace fs = boost::filesystem;  /**  * \brief   Return the filenames of all files that have the specified extension  *          in the specified directory and all subdirectories.  */ std::vector<fs::path> get_all(fs::path const & root, std::string const & ext) {     std::vector<fs::path> paths;      if (fs::exists(root) && fs::is_directory(root))     {         for (auto const & entry : fs::recursive_directory_iterator(root))         {             if (fs::is_regular_file(entry) && entry.path().extension() == ext)                 paths.emplace_back(entry.path().filename());         }     }      return paths; }              
like image 92
Gigi Avatar answered Sep 24 '22 10:09

Gigi