I don't know how to use filesystem to look for .txt files c++

Viewed 496

I would like to use std::filesystem in my project, which will allow me to show .txt files in the current directory (I use Ubuntu, I don't need a Windows function because I have already seen one on StackOverflow).

Here is my GitHub repo:

https://github.com/jaroslawroszyk/-how-many-pages-per-day

I have a fix for this problem like this:

void showFilesTxt()
{
    DIR *d;
    char *p1, *p2;
    int ret;
    struct dirent *dir;
    d = opendir(".");
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            p1 = strtok(dir->d_name, ".");
            p2 = strtok(NULL, ".");
            if (p2 != NULL)
            {
                ret = strcmp(p2, "txt");
                if (ret == 0)
                {
                    std::cout << p1 << "\n";
                }
            }
        }
        closedir(d);
    }
}

But the code I enter here would like to use C++17, but I don't know how to find the .txt files, now I wrote:

for (auto &fn : std::filesystem::directory_iterator("."))
    if (std::filesystem::is_regular_file(fn))
    {
        std::cout << fn.path() << '\n';
    }
2 Answers

If you look into the reference (https://en.cppreference.com/w/cpp/filesystem/path) you will find the extension() method on paths (https://en.cppreference.com/w/cpp/filesystem/path/extension) which returns you the file's extension. Now you simply need to use the string() function on the path's extension and compare the string.

Something like

for (auto& p : std::filesystem::directory_iterator(".")) {
    if (p.is_regular_file()) {
        if (p.path().extension().string() == ".txt") {
            std::cout << p << std::endl;
        }
    }
}

In C++20, you can just check if the path().string() ends with .txt by using the std::string::ends_with member function:

#include <filesystem>
#include <iostream>

int main() {
    for(auto& de : std::filesystem::directory_iterator(".")) {
        if(de.is_regular_file() && de.path().string().ends_with(".txt")) {
            std::cout << de << '\n';     // or `de.path().string()
        }
    }
}
Related