Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

c++ - 如何使用C或C ++获取目录中的文件列表?(How can I get the list of files in a directory using C or C++?)

How can I determine the list of files in a directory from inside my C or C++ code?

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

I'm not allowed to execute the ls command and parse the results from within my program.

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

  ask by samoz translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In small and simple tasks I do not use boost, I use dirent.h which is also available for windows:

(在小的简单任务中,我不使用boost,而是使用dirent.h ,它也可用于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
", ent->d_name);
  }
  closedir (dir);
} else {
  /* could not open directory */
  perror ("");
  return EXIT_FAILURE;
}

It is just a small header file and does most of the simple stuff you need without using a big template-based approach like boost(no offence, I like boost!).

(它只是一个很小的头文件,不需要使用boost这样的基于模板的大方法(不需要冒犯,我喜欢boost!)就可以完成您所需的大多数简单操作。)

The author of the windows compatibility layer is Toni Ronkko.

(Windows兼容性层的作者是Toni Ronkko。)

In Unix, it is a standard header.

(在Unix中,它是一个标准头。)

UPDATE 2017 :

(更新2017 :)

In C++17 there is now an official way to list files of your file system: std::filesystem .

(在C ++ 17中,现在有一种正式的方法来列出文件系统的文件: std::filesystem 。)

There is an excellent answer from Shreevardhan below with this source code:

(下面的源代码在Shreevardhan中有一个很好的答案:)

#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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...