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

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


当前回答

为什么不使用glob()?

#include <glob.h>

glob_t glob_result;
glob("/your_directory/*",GLOB_TILDE,NULL,&glob_result);
for(unsigned int i=0; i<glob_result.gl_pathc; ++i){
  cout << glob_result.gl_pathv[i] << endl;
}

其他回答

尝试x平台方法

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

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

一个函数就足够了,你不需要使用任何第三方库(对于Windows)。

#include <Windows.h>

vector<string> get_all_files_names_within_folder(string folder)
{
    vector<string> names;
    string search_path = folder + "/*.*";
    WIN32_FIND_DATA fd; 
    HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd); 
    if(hFind != INVALID_HANDLE_VALUE) { 
        do { 
            // read all (real) files in current folder
            // , delete '!' read other 2 default folder . and ..
            if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) {
                names.push_back(fd.cFileName);
            }
        }while(::FindNextFile(hFind, &fd)); 
        ::FindClose(hFind); 
    } 
    return names;
}

PS:正如@Sebastian提到的,你可以改变*。*到*。ext,以便只获得该目录中的ext文件(即特定类型的文件)。

看看这个使用win32 api的类。只需要构造一个实例,提供您想要清单的文件夹名,然后调用getNextFile方法从目录中获取下一个文件名。我认为它需要windows.h和stdio.h。

class FileGetter{
    WIN32_FIND_DATAA found; 
    HANDLE hfind;
    char folderstar[255];       
    int chk;

public:
    FileGetter(char* folder){       
        sprintf(folderstar,"%s\\*.*",folder);
        hfind = FindFirstFileA(folderstar,&found);
        //skip .
        FindNextFileA(hfind,&found);        
    }

    int getNextFile(char* fname){
        //skips .. when called for the first time
        chk=FindNextFileA(hfind,&found);
        if (chk)
            strcpy(fname, found.cFileName);     
        return chk;
    }

};

我试图遵循两个回答中给出的示例,可能值得注意的是,似乎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 <<会导致丢失重载错误。

简单地在Linux中使用ASCI C风格的代码

#include <bits/stdc++.h>
#include <dirent.h>
using namespace std;

int main(){
    DIR *dpdf;
    struct dirent *epdf;
    dpdf = opendir("./");
    
    if (dpdf != NULL){
    while (epdf = readdir(dpdf)){
        cout << epdf->d_name << std::endl;
    }
    }
    closedir(dpdf);
    return 0;
}

希望这能有所帮助!