【问题标题】:I don't know how to use filesystem to look for .txt files c++我不知道如何使用文件系统来查找 .txt 文件 c++
【发布时间】:2021-09-17 11:08:39
【问题描述】:

我想在我的项目中使用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';
    }

【问题讨论】:

  • 我假设C++17标签意味着你不能使用C++20库添加?
  • 是的,你可以使用 c++20

标签: c++ c++17 txt std-filesystem


【解决方案1】:

如果您查看参考 (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;
        }
    }
}

【讨论】:

  • 请注意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
  • 通过@RemyLebeau 指出的建议修复,我认为这是一个比我更好的答案。我已经赞成它,但我敦促 OP 选择你的作为接受的答案,以鼓励未来的读者使用它 - 如果你做出必要的改变。
【解决方案2】:

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

【讨论】:

  • 如何去掉开头的“./”和后缀,使其在程序运行中不可见
  • @JarosławRoszyk 如果文件都在同一个目录中,您可以使用std::cout &lt;&lt; de.path().filename() 仅获取路径的文件名部分。如果您稍后决定进行递归搜索,那么仅打印文件名可能会造成混淆。
  • 非常感谢,可以用c++ 20 但是我还没研究过,就停在c++ 11/14
  • @JarosławRoszyk 不客气!很高兴它有帮助!如果您查看std::filesystem::path,您有许多帮助函数,您可以用它们来做有趣的事情。 path 具有迭代器,因此您也可以遍历路径中的各个组件(目录)。
  • 我要见见这位朋友哈哈
猜你喜欢
  • 2021-11-16
  • 2022-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-24
  • 1970-01-01
相关资源
最近更新 更多