c++ - 如何使用 C 或 C++ 获取目录中的文件列表?

标签 c++ c file directory

如何从 C 或 C++ 代码中确定目录中的文件列表?

我不允许在程序中执行 ls 命令并解析结果。

最佳答案

2017 年更新:

在 C++17 中,现在有一种列出文件系统文件的官方方法:std::filesystemShreevardhan 有一个很好的答案下面是这个源代码:

#include <string>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main()
{
    std::string path = "/path/to/directory";
    for (const auto & entry : fs::directory_iterator(path))
        std::cout << entry.path() << std::endl;
}

旧答案:

在小而简单的任务中,我不使用 boost,而是使用 dirent.h。它可作为 UNIX 中的标准 header 使用,也可通过 compatibility layer created by Toni Rönkkö 用于 Windows。 .

DIR *dir;
struct dirent *ent;
if ((dir = opendir ("c:\\src\\")) != NULL) {
  /* print all the files and directories within directory */
  while ((ent = readdir (dir)) != NULL) {
    printf ("%s\n", ent->d_name);
  }
  closedir (dir);
} else {
  /* could not open directory */
  perror ("");
  return EXIT_FAILURE;
}

它只是一个小头文件,可以完成您需要的大部分简单功能,而无需使用像 boost 这样的基于模板的大方法(无意冒犯,我喜欢 boost!)。

关于c++ - 如何使用 C 或 C++ 获取目录中的文件列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53536417/

相关文章:

c - 使用 gdb 调试从 stdin 读取输入的交互式程序

c - undefined reference 'yylex' bison 错误

java - log4j:错误 setFile(null,true)调用失败。java.io.FileNotFoundException:

java - 如何在 Java 中复制对 File 对象的引用

c++ - 文件输入输出

C++ 在主函数之外使用 "cout"?

c - 获取字符并将其转换为字符串

c++ - 将 vector<int> 中的每个 int 添加到字符串

c++ - 如何在 Windows 应用程序中截取屏幕截图?

c++ - 为什么堆而不是排序容器