Skip to content

[cpp, c++] std::filesystem search extension

namespace fs = std::filesystem;

Use fs::recursive_directory_iterator

fs::recursive_directory_iterator iterates all subdirectories recursively of a directory.

is_directory, is_regular_file, extension

is_directory - check if the file status or path corresponds to a directory.

fs::is_directory(?);
fs::directory_entry::is_directory();

is_regular_file - check if the file status or path corresponds to a regular file.

fs::is_regular_file(?);
fs::directory_entry::is_regular_file();

Use utxcpp

utx::printe

utx::print_all

Code cpp/c++

#include <utxcpp/core.hpp>
#include <vector>
#include <filesystem>

namespace fs = std::filesystem;

int main(int argc, char * argv[])
try
{
        if (argc != 3)
                throw std::runtime_error{"prog <path> <search extension>"};
        const fs::path path = argv[1];
        const std::string ext = argv[2];
        std::vector<fs::path> searched;
        for (const auto & entry: fs::recursive_directory_iterator{path})
        {
                if (
                        ! entry.is_directory() && entry.is_regular_file()
                        && entry.path().has_filename()
                        && entry.path().extension() == ext
                )
                {
                        searched.push_back(entry.path());
                }
        }
        utx::print_all(searched);
}
catch (std::exception & error)
{
        utx::printe("[std::exception]\n", error.what());
        return 1;
}

 

 

 

Trackbacks

No Trackbacks

Comments

Display comments as Linear | Threaded

No comments

Add Comment

E-Mail addresses will not be displayed and will only be used for E-Mail notifications.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

Form options

Submitted comments will be subject to moderation before being displayed.

@cppfx.xyz