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 中可作为标准头文件使用,也可通过 compatibility layer created by Toni Ronkko 用于 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/612097/

相关文章:

c++ - C++ 中的正则表达式抛出错误 "Invalid special open parenthesis."

c++ - 使用 OpenCV 计算 X 和 Y 导数的绝对值

javascript - 将 Dropzone.js 与其他表单字段集成到 html 表单中

python - 如何将 Traceback 错误信息保存到文件中

c++ - 使用类的成员函数时程序崩溃,但在 main() 中直接实现该函数时不会崩溃

c++ - 使用多态基类(包含虚函数)访问时数组元素的类型

c - 在unix中执行wc命令的程序。字数错误

C:地址运算符 (&) 产生一个指针(地址 + 类型)还是只是一个地址?

c - 确定当前用户帐户属于哪个组?

PHP:将文件从域 move 到子域