如何在C++中获取目录中的文件列表?

DSh*_*ook 45 c++ directory file

如何获取目录中的文件列表,以便可以处理每个文件?

Tho*_*ini 58

这是我使用的:

/* Returns a list of files in a directory (except the ones that begin with a dot) */

void GetFilesInDirectory(std::vector<string> &out, const string &directory)
{
#ifdef WINDOWS
    HANDLE dir;
    WIN32_FIND_DATA file_data;

    if ((dir = FindFirstFile((directory + "/*").c_str(), &file_data)) == INVALID_HANDLE_VALUE)
        return; /* No files found */

    do {
        const string file_name = file_data.cFileName;
        const string full_file_name = directory + "/" + file_name;
        const bool is_directory = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;

        if (file_name[0] == '.')
            continue;

        if (is_directory)
            continue;

        out.push_back(full_file_name);
    } while (FindNextFile(dir, &file_data));

    FindClose(dir);
#else
    DIR *dir;
    class dirent *ent;
    class stat st;

    dir = opendir(directory);
    while ((ent = readdir(dir)) != NULL) {
        const string file_name = ent->d_name;
        const string full_file_name = directory + "/" + file_name;

        if (file_name[0] == '.')
            continue;

        if (stat(full_file_name.c_str(), &st) == -1)
            continue;

        const bool is_directory = (st.st_mode & S_IFDIR) != 0;

        if (is_directory)
            continue;

        out.push_back(full_file_name);
    }
    closedir(dir);
#endif
} // GetFilesInDirectory
Run Code Online (Sandbox Code Playgroud)

  • 您为此工作包含哪些标题? (5认同)

Joh*_*itb 36

标准C++没有提供这样做的方法.但是boost::filesystem可以这样做:http://www.boost.org/doc/libs/1_37_0/libs/filesystem/example/simple_ls.cpp


Chr*_*anz 26

这是Linux上的C示例.那就是,如果你在Linux上并且不介意在ANSI C中做这么小的一点.

#include <dirent.h>

DIR *dpdf;
struct dirent *epdf;

dpdf = opendir("./");
if (dpdf != NULL){
   while (epdf = readdir(dpdf)){
      printf("Filename: %s",epdf->d_name);
      // std::cout << epdf->d_name << std::endl;
   }
}
closedir(dpdf);
Run Code Online (Sandbox Code Playgroud)

  • 之后不要忘记'closedir(dpdf)` (12认同)

Adr*_*ddy 6

C++11/Linux 版本:

#include <dirent.h>

if (auto dir = opendir("some_dir/")) {
    while (auto f = readdir(dir)) {
        if (!f->d_name || f->d_name[0] == '.')
            continue; // Skip everything that starts with a dot

        printf("File: %s\n", f->d_name);
    }
    closedir(dir);
}
Run Code Online (Sandbox Code Playgroud)