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

Eri*_*s69 3 c++ c++17 std-filesystem txt

我想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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

hef*_*efe 5

如果您查看参考(https://en.cppreference.com/w/cpp/filesystem/pathextension() ),您将在路径(https://en.cppreference.com/w/cpp/filesystem/path )上找到该方法/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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,“directory_iterator”取消引用“directory_entry”,而不是“path”,因此您需要使用“p.path().extension()”而不是“p.extension()”。另外,您可以使用“p.is_regular_file()”而不是“std::filesystem::is_regular_file(p.path())”。并且,您可以使用 `string() == ".txt"` 而不是 `string().compare(".txt") == 0`。 (3认同)