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

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


当前回答

这个答案应该适用于Windows用户在使用Visual Studio和任何其他答案时遇到的问题。

Download the dirent.h file from the github page. But is better to just use the Raw dirent.h file and follow my steps below (it is how I got it to work). Github page for dirent.h for Windows: Github page for dirent.h Raw Dirent File: Raw dirent.h File Go to your project and Add a new Item (Ctrl+Shift+A). Add a header file (.h) and name it dirent.h. Paste the Raw dirent.h File code into your header. Include "dirent.h" in your code. Put the below void filefinder() method in your code and call it from your main function or edit the function how you want to use it. #include <stdio.h> #include <string.h> #include "dirent.h" string path = "C:/folder"; //Put a valid path here for folder void filefinder() { DIR *directory = opendir(path.c_str()); struct dirent *direntStruct; if (directory != NULL) { while (direntStruct = readdir(directory)) { printf("File Name: %s\n", direntStruct->d_name); //If you are using <stdio.h> //std::cout << direntStruct->d_name << std::endl; //If you are using <iostream> } } closedir(directory); }

其他回答

尝试x平台方法

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

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

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

塞萨尔·亚历杭德罗·蒙特罗·奥罗斯科回答。

简单中有美,通过添加/s键,我们还可以遍历子目录。

system("dir /n /b /s * > file_names.txt");
char **getKeys(char *data_dir, char* tablename, int *num_keys)
{
    char** arr = malloc(MAX_RECORDS_PER_TABLE*sizeof(char*));
int i = 0;
for (;i < MAX_RECORDS_PER_TABLE; i++)
    arr[i] = malloc( (MAX_KEY_LEN+1) * sizeof(char) );  


char *buf = (char *)malloc( (MAX_KEY_LEN+1)*sizeof(char) );
snprintf(buf, MAX_KEY_LEN+1, "%s/%s", data_dir, tablename);

DIR* tableDir = opendir(buf);
struct dirent* getInfo;

readdir(tableDir); // ignore '.'
readdir(tableDir); // ignore '..'

i = 0;
while(1)
{


    getInfo = readdir(tableDir);
    if (getInfo == 0)
        break;
    strcpy(arr[i++], getInfo->d_name);
}
*(num_keys) = i;
return arr;
}

对于C的唯一解决方案,请检查这个。它只需要一个额外的头文件:

https://github.com/cxong/tinydir

tinydir_dir dir;
tinydir_open(&dir, "/path/to/dir");

while (dir.has_next)
{
    tinydir_file file;
    tinydir_readfile(&dir, &file);

    printf("%s", file.name);
    if (file.is_dir)
    {
        printf("/");
    }
    printf("\n");

    tinydir_next(&dir);
}

tinydir_close(&dir);

与其他选项相比,以下是一些优势:

它是可移植的-包装POSIX的dirent和Windows的FindFirstFile 它在可用的地方使用readdir_r,这意味着它(通常)是线程安全的 通过相同的UNICODE宏支持Windows UTF-16 它是C90,所以即使是非常古老的编译器也可以使用它