Ramy Sameh
Ramy Sameh

Reputation: 301

Searching for files with specific extension - using recursive_directory_iterator - <filesystem> library

I am trying to search for files with certain extensions in a directory, using the "recursive_directory_iterator" function inside library.

I am using Visual Studio Express 2017.

I am following the code in this answer: https://stackoverflow.com/a/47975458/4145697

Here is my code:

#include <windows.h>
#include <iostream>
#include <filesystem>
#include <string>
void get_list_of_files(void)
{
    std::string constructed_path_str_dbg = "C:\\Cpp_trials\\Trials\\Debug\\baseline\\cpp_files_trial";
    std::string ext(".sample");
    for (auto& p : fs::recursive_directory_iterator(constructed_path_str_after))
    {
        if (p.path().extension() == ext())  // errors E0980 and C2064
            std::cout << p << '\n';         // errors E0349 and C2679
    }
}

But I am having the following compilation errors:

E0980   call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type 

E0349   no operator "<<" matches these operands 

C2064   term does not evaluate to a function taking 0 arguments 

C2679   binary '<<': no operator found which takes a right-hand operand of type 'const std::filesystem::directory_entry' (or there is no acceptable conversion)

Upvotes: 1

Views: 1674

Answers (1)

Barrnet Chou
Barrnet Chou

Reputation: 1923

According to the code you provided, I tested and modified it.

  1. Change constructed_path_str_after to constructed_path_str_dbg

  2. Change ext() to ext

The following are my test results:

#include <fstream>
#include <iostream>
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;

int main()
{
    std::string constructed_path_str_dbg = "C:\\Cpp_trials\\Trials\\Debug\\baseline\\cpp_files_trial";
    std::string ext(".txt");
    for (auto& p : fs::recursive_directory_iterator(constructed_path_str_dbg))
    {
        if (p.path().extension() == ext)  
            std::cout << p << '\n';        
    }

    return 0;
}

enter image description here

I hope to know why you would use constructed_path_str_after, because this is related to your problem solving. I can only speculate on your needs based on the existing code.

Upvotes: 2

Related Questions