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

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


当前回答

Shreevardhan的设计也适用于遍历子目录:

#include <string>
#include <iostream>
#include <filesystem>

using namespace std;
namespace fs = filesystem;
int main()
{
    string path = "\\path\\to\\directory";
    // string path = "/path/to/directory";
    for (auto & p : fs::recursive_directory_iterator(path))
        cout << p.path() << endl;
}

编译:cl /EHsc /W4 /WX /std:c++17 ListFiles.cpp

其他回答

系统调用它!

system( "dir /b /s /a-d * > file_names.txt" );

那就读一读文件。

编辑:这个答案应该被认为是一种hack,但如果你没有更优雅的解决方案,它确实有用(尽管是在特定的平台上)。

我试图遵循两个回答中给出的示例,可能值得注意的是,似乎std::filesystem::directory_entry已被更改为不重载<<操作符。而不是std::cout << p << std::endl;我必须使用以下能够编译并让它工作:

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

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

试图将p单独传递给std::cout <<会导致丢失重载错误。

尝试x平台方法

http://www.boost.org/doc/libs/1_38_0/libs/filesystem/doc/index.htm

或者只是使用特定于操作系统的文件。

我认为,下面的代码片段可以用来列出所有的文件。

#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>

int main(int argc, char** argv) { 
    list_dir("myFolderName");
    return EXIT_SUCCESS;
}  

static void list_dir(const char *path) {
    struct dirent *entry;
    DIR *dir = opendir(path);
    if (dir == NULL) {
        return;
    }

    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n",entry->d_name);
    }

    closedir(dir);
}

这是使用的结构(出现在direct .h中):

struct dirent {
    ino_t d_ino; /* inode number */
    off_t d_off; /* offset to the next dirent */
    unsigned short d_reclen; /* length of this record */
    unsigned char d_type; /* type of file */
    char d_name[256]; /* filename */
};

GNU手册FTW

http://www.gnu.org/software/libc/manual/html_node/Simple-Directory-Lister.html#Simple-Directory-Lister

此外,有时直接找到源头是件好事(双关)。通过查看Linux中一些最常见命令的内部结构,您可以学到很多东西。我在github上建立了一个GNU coreutils的简单镜像(供阅读)。

https://github.com/homer6/gnu_coreutils/blob/master/src/ls.c

也许这并不能解决Windows的问题,但是通过使用这些方法,可以实现使用Unix变体的许多情况。

希望这对你有所帮助……