我不知道如何使用文件系统来查找 .txt 文件 c++

问题描述

我想在我的项目中使用 std::filesystem,这将允许我在当前目录中显示 .txt 文件(我使用 Ubuntu,我不需要 Windows 功能,因为我已经在 StackOverflow 上看到过一个)。

这是我的 GitHub 存储库:

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

我有一个解决这个问题的方法

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);
    }
}

但是我这里输入的代码想使用C++17,但是我不知道如何找到.txt文件,现在我写了:

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

解决方法

如果您查看参考文献 (https://en.cppreference.com/w/cpp/filesystem/path),您会发现路径 (https://en.cppreference.com/w/cpp/filesystem/path/extension) 上的 extension() 方法会返回文件的扩展名。现在您只需要在路径的扩展名上使用 string() 函数并比较字符串。

类似的东西

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

在 C++20 中,您可以使用 std::string::ends_with 成员函数检查 path().string() 是否以 .txt 结尾:

#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()
        }
    }
}