4

I've got a task in which I get a string and a path to a directory and I must open every .txt file from that directory and all subdirectories and print all the .txt in which I could find that string.

I managed to get the path to those .txt files in the directory, but I cannot go further to the subdirectories. Is there any command to do this? In Python I used:

for path, dirs, files in os.walk(dirPath):
        for f in files:
            if f.endswith('.txt'):

But i cannot find a command like that in c++.

Thanks

SnuKies
  • 1,578
  • 1
  • 16
  • 37
  • 1
    `std::filesystem` is only a proposition for C++1z, so until it is 2017, please specify platform you are using – myaut May 12 '16 at 21:40
  • 1
    Or install and configure Boost to get [`boost::filesystem`](http://www.boost.org/doc/libs/1_60_0/libs/filesystem/doc/reference.html). Might be easier to fulfill @myaut 's request and specify the platform. – user4581301 May 12 '16 at 21:50
  • 2
    Not quite a dupe: http://stackoverflow.com/questions/612097/how-can-i-get-the-list-of-files-in-a-directory-using-c-or-c. Listing directories on the most common platforms are covered in one answer or another. From there you should be able to filter out the txt files easily. – user4581301 May 12 '16 at 21:51
  • `GCC` has `filesystem` now `(5.3.1)` – Galik May 12 '16 at 22:10

1 Answers1

2

For compilers that support the filesystem Technical Specification which has now been accepted into C++17 this can be done as follows:

#include <string>
#include <iostream>
#include <experimental/filesystem> // Later (C++17) just <filesystem>

namespace fs = std::experimental::filesystem;

int main(int, char** argv)
{
    std::string dir = ".";

    if(argv[1])
        dir = argv[1];

    for(auto& item: fs::recursive_directory_iterator(dir))
    {
        if(!fs::is_regular_file(item.path())
        || item.path().extension() != ".txt")
            continue;

        // open text file here
        std::cout << "Found text file: " << item.path().string() << '\n';
    }
}
Galik
  • 47,303
  • 4
  • 80
  • 117