【问题标题】:Find specific file type in a directory (C++)在目录中查找特定文件类型 (C++)
【发布时间】:2015-01-07 18:46:25
【问题描述】:

我想制作一个程序,可以搜索我计算机上的特定文件夹以查找某些文件。在这种情况下,我希望它查找文本文件。我听说一些消息来源声称这可以使用标准 C++ 库来完成。如果是这样,我该怎么做呢?我相信工作代码应该是这样的:

string path = "C:\\MyFolder\\";

while(/*Searching through the directory*/)
{
    if (/*File name ends with .txt*/)
    {
        /*Do something*/
    }
}

【问题讨论】:

  • 标准 c++ 库不提供与平台无关的文件浏览方式。您必须为您当前的操作系统找到示例。编辑:但是,如果您正在寻找独立于平台的包装类,请查看 WxWidgets。

标签: c++ file search directory


【解决方案1】:

不支持使用标准库中的目录。然而,努力将Boost.Filesystem 合并到 C++17 标准中。目前,您可以直接使用Boost

#include <iostream>

#include <boost/filesystem.hpp>
#include <boost/algorithm/string/predicate.hpp>

int main(int argc, char* argv[])
{
  namespace fs = boost::filesystem;
  namespace ba = boost::algorithm;

  fs::path dir_path(".");

  for (const auto& entry : fs::directory_iterator(dir_path)) {
    if (fs::is_regular_file(entry)) {
      std::string path = entry.path().string();
      if (ba::ends_with(path, ".txt")) {
        // Do something with entry or just print the path
        std::cout << path << std::endl;
      }
    }
  }
}

更新:

要编译 sn-p,您需要安装 Boost(并编译,文件系统不是仅头文件)。按照教程here。然后确保与boost_filesystem链接:

g++ -std=c++11 -Wall test.cc -lboost_filesystem && ./a.out

并且不要忘记在同一目录中创建一些.txt 文件,以便程序有一些东西可以咀嚼。

【讨论】:

  • 我下载了 Boost 1.57 来尝试这个,但是当包含两个 .hpp 文件时,它会出现许多错误,例如“命名空间 boost 没有成员文件系统”。为了编译代码,我还需要包含更多文件或库吗?如果是这样,我在哪里可以找到它们?
猜你喜欢
  • 2023-01-21
  • 2011-10-26
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-09
  • 1970-01-01
相关资源
最近更新 更多