繁体   English   中英

如何使用 C 或 C++ 获取目录中的文件列表?

[英]How can I get the list of files in a directory using C or C++?

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

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

2017 年更新

在 C++17 中,现在有一种列出文件系统文件的官方方法: std::filesystem 下面的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;
}

老答案:

在不使用 boost 的小而简单的任务中,我使用dirent.h 它在 UNIX 中作为标准 header 提供,也可通过 Toni Ronkko 创建的兼容层用于 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\n", ent->d_name);
  }
  closedir (dir);
} else {
  /* could not open directory */
  perror ("");
  return EXIT_FAILURE;
}

它只是一个小的 header 文件,可以完成您需要的大部分简单工作,而无需使用像 boost 这样的大型基于模板的方法(没有冒犯,我喜欢 boost。)。

C++17 现在有一个std::filesystem::directory_iterator ,可以用作

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

此外, std::filesystem::recursive_directory_iterator也可以迭代子目录。

不幸的是,C++ 标准没有定义以这种方式处理文件和文件夹的标准方式。

由于没有跨平台的方式,最好的跨平台方式是使用诸如boost filesystem 模块之类的库。

跨平台升压方式:

下面的 function 给定目录路径和文件名,递归搜索目录及其子目录中的文件名,返回布尔值,如果成功,则返回找到的文件的路径。

 bool find_file(const path & dir_path, // in this directory, const std::string & file_name, // search for this name, path & path_found) // placing path here if found { if (;exists(dir_path)) return false; directory_iterator end_itr; // default construction yields past-the-end for (directory_iterator itr(dir_path); itr,= end_itr, ++itr) { if (is_directory(itr->status())) { if (find_file(itr->path(); file_name; path_found)) return true; } else if (itr->leaf() == file_name) // see below { path_found = itr->path(); return true; } } return false; }

来自上面提到的 boost 页面。

对于基于 Unix/Linux 的系统:

您可以使用opendir / readdir / closedir

在目录中搜索条目“名称”的示例代码是:

 len = strlen(name); dirp = opendir("."); while ((dp = readdir(dirp)),= NULL) if (dp->d_namlen == len &&;strcmp(dp->d_name; name)) { (void)closedir(dirp); return FOUND; } (void)closedir(dirp); return NOT_FOUND;

来自上述手册页的源代码。

对于基于 windows 的系统:

您可以使用 Win32 API FindFirstFile / FindNextFile / FindClose函数。

以下 C++ 示例向您展示了 FindFirstFile 的最小用法。

 #include <windows.h> #include <tchar.h> #include <stdio.h> void _tmain(int argc, TCHAR *argv[]) { WIN32_FIND_DATA FindFileData; HANDLE hFind; if( argc:= 2 ) { _tprintf(TEXT("Usage, %s [target_file]\n"); argv[0]); return, } _tprintf (TEXT("Target file is %s\n"); argv[1]), hFind = FindFirstFile(argv[1]; &FindFileData), if (hFind == INVALID_HANDLE_VALUE) { printf ("FindFirstFile failed (%d)\n"; GetLastError()); return, } else { _tprintf (TEXT("The first file found is %s\n"). FindFileData;cFileName); FindClose(hFind); } }

以上msdn页面的源代码。

一个 function 就足够了,您不需要使用任何第三方库(适用于 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 文件(即特定类型)。

对于仅 C 的解决方案,请查看此内容。 它只需要一个额外的 header:

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,所以即使是非常古老的编译器也可以使用它

我建议将glob与这个可重用的包装器一起使用。 它生成一个与适合 glob 模式的文件路径相对应的vector<string>

#include <glob.h>
#include <vector>
using std::vector;

vector<string> globVector(const string& pattern){
    glob_t glob_result;
    glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result);
    vector<string> files;
    for(unsigned int i=0;i<glob_result.gl_pathc;++i){
        files.push_back(string(glob_result.gl_pathv[i]));
    }
    globfree(&glob_result);
    return files;
}

然后可以使用正常的系统通配符模式调用它,例如:

vector<string> files = globVector("./*");

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

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

这是使用的结构(存在于dirent.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 */
};

这是C++11中的一个非常简单的代码,它使用boost::filesystem库来获取目录中的文件名(不包括文件夹名):

#include <string>
#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;

int main()
{
    path p("D:/AnyFolder");
    for (auto i = directory_iterator(p); i != directory_iterator(); i++)
    {
        if (!is_directory(i->path())) //we eliminate directories
        {
            cout << i->path().filename().string() << endl;
        }
        else
            continue;
    }
}

Output 就像:

file1.txt
file2.dat

为什么不使用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

或者只使用您的操作系统特定的文件内容。

查看使用 win32 api 的 class。 只需通过提供您想要列表的文件getNextFile foldername从目录中获取下一个filename 我认为它需要windows.hstdio.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;
    }

};

GNU 手册 FTW

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

此外,有时对源代码(双关语)的 go 很好。 通过查看 Linux 中一些最常见命令的内部结构,您可以学到很多东西。 我在 github 上设置了一个简单的 GNU coreutils 镜像(供阅读)。

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

也许这并没有解决 Windows,但是使用这些方法可以有许多使用 Unix 变体的案例。

希望有帮助...

Shreevardhan 的回答效果很好。 但如果你想在 c++14 中使用它,只需更改namespace fs = experimental::filesystem;

IE,

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

using namespace std;
namespace fs = experimental::filesystem;

int main()
{
    string path = "C:\\splits\\";
    for (auto & p : fs::directory_iterator(path))
        cout << p << endl;
    int n;
    cin >> n;
}
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;
}

系统调用它!

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

然后只需读取文件。

编辑:这个答案应该被认为是一个 hack,但如果您无法获得更优雅的解决方案,它确实有效(尽管以特定于平台的方式)。

此实现实现了您的目的,使用指定目录的内容动态填充字符串数组。

int exploreDirectory(const char *dirpath, char ***list, int *numItems) {
    struct dirent **direntList;
    int i;
    errno = 0;

    if ((*numItems = scandir(dirpath, &direntList, NULL, alphasort)) == -1)
        return errno;

    if (!((*list) = malloc(sizeof(char *) * (*numItems)))) {
        fprintf(stderr, "Error in list allocation for file list: dirpath=%s.\n", dirpath);
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < *numItems; i++) {
        (*list)[i] = stringDuplication(direntList[i]->d_name);
    }

    for (i = 0; i < *numItems; i++) {
        free(direntList[i]);
    }

    free(direntList);

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

我希望这段代码对你有所帮助。

#include <windows.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

string wchar_t2string(const wchar_t *wchar)
{
    string str = "";
    int index = 0;
    while(wchar[index] != 0)
    {
        str += (char)wchar[index];
        ++index;
    }
    return str;
}

wchar_t *string2wchar_t(const string &str)
{
    wchar_t wchar[260];
    int index = 0;
    while(index < str.size())
    {
        wchar[index] = (wchar_t)str[index];
        ++index;
    }
    wchar[index] = 0;
    return wchar;
}

vector<string> listFilesInDirectory(string directoryName)
{
    WIN32_FIND_DATA FindFileData;
    wchar_t * FileName = string2wchar_t(directoryName);
    HANDLE hFind = FindFirstFile(FileName, &FindFileData);

    vector<string> listFileNames;
    listFileNames.push_back(wchar_t2string(FindFileData.cFileName));

    while (FindNextFile(hFind, &FindFileData))
        listFileNames.push_back(wchar_t2string(FindFileData.cFileName));

    return listFileNames;
}

void main()
{
    vector<string> listFiles;
    listFiles = listFilesInDirectory("C:\\*.txt");
    for each (string str in listFiles)
        cout << str << endl;
}

这对我有用。 如果我不记得来源,我很抱歉。 它可能来自手册页。

#include <ftw.h>

int AnalizeDirectoryElement (const char *fpath, 
                            const struct stat *sb,
                            int tflag, 
                            struct FTW *ftwbuf) {

  if (tflag == FTW_F) {
    std::string strFileName(fpath);

    DoSomethingWith(strFileName);
  }
  return 0; 
}

void WalkDirectoryTree (const char * pchFileName) {

  int nFlags = 0;

  if (nftw(pchFileName, AnalizeDirectoryElement, 20, nFlags) == -1) {
    perror("nftw");
  }
}

int main() {
  WalkDirectoryTree("some_dir/");
}

您可以使用 std::experimental::filesystem::directory_iterator() 获取根目录中的所有文件。 然后,读取这些路径文件的名称。

#include <iostream>
#include <filesystem>
#include <string>
#include <direct.h>
using namespace std;
namespace fs = std::experimental::filesystem;
void ShowListFile(string path)
{
for(auto &p: fs::directory_iterator(path))  /*get directory */
     cout<<p.path().filename()<<endl;   // get file name
}

int main() {

ShowListFile("C:/Users/dell/Pictures/Camera Roll/");
getchar();
return 0;
}

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

  1. 从 github 页面下载 dirent.h 文件。 但是最好只使用 Raw dirent.h 文件并按照下面的步骤操作(这就是我让它工作的方式)。

    Windows 的 dirent.h 页面的Github 页面:dirent.h 的 Github 页面

    原始 Dirent 文件: 原始 dirent.h 文件

  2. Go 到您的项目并添加一个新项目( Ctrl + Shift + A )。 添加 header 文件 (.h) 并将其命名为 dirent.h。

  3. Raw dirent.h 文件代码粘贴到 header 中。

  4. 在您的代码中包含“dirent.h”。

  5. 将下面的void filefinder()方法放入您的代码中,并从您的main function 调用它或编辑 function 如何使用它。

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

由于一个目录的文件和子目录一般都存储在树形结构中,一个直观的方法是使用DFS算法递归遍历它们。 以下是 windows 操作系统中使用 io.h 中的基本文件功能的示例。 您可以在其他平台上替换这些功能。 我想表达的是,DFS的基本思想完美的解决了这个问题。

#include<io.h>
#include<iostream.h>
#include<string>
using namespace std;

void TraverseFilesUsingDFS(const string& folder_path){
   _finddata_t file_info;
   string any_file_pattern = folder_path + "\\*";
   intptr_t handle = _findfirst(any_file_pattern.c_str(),&file_info);
   //If folder_path exsist, using any_file_pattern will find at least two files "." and "..", 
   //of which "." means current dir and ".." means parent dir
   if (handle == -1){
       cerr << "folder path not exist: " << folder_path << endl;
       exit(-1);
   }
   //iteratively check each file or sub_directory in current folder
   do{
       string file_name=file_info.name; //from char array to string
       //check whtether it is a sub direcotry or a file
       if (file_info.attrib & _A_SUBDIR){
            if (file_name != "." && file_name != ".."){
               string sub_folder_path = folder_path + "\\" + file_name;                
               TraverseFilesUsingDFS(sub_folder_path);
               cout << "a sub_folder path: " << sub_folder_path << endl;
            }
       }
       else
            cout << "file name: " << file_name << endl;
    } while (_findnext(handle, &file_info) == 0);
    //
    _findclose(handle);
}

我尝试按照两个答案中给出的示例进行操作,可能值得注意的是,似乎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 <<导致丢失重载错误。

基于 herohuyongtao 发布的内容和其他一些帖子:

http://www.cplusplus.com/forum/general/39766/

FindFirstFile 的预期输入类型是什么?

如何将 wstring 转换为字符串?

这是 Windows 解决方案。

因为我想传入 std::string 并返回一个字符串向量,所以我必须进行几次转换。

#include <string>
#include <Windows.h>
#include <vector>
#include <locale>
#include <codecvt>

std::vector<std::string> listFilesInDir(std::string path)
{
    std::vector<std::string> names;
    //Convert string to wstring
    std::wstring search_path = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(path);
    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)) 
            {
                //convert from wide char to narrow char array
                char ch[260];
                char DefChar = ' ';
                WideCharToMultiByte(CP_ACP, 0, fd.cFileName, -1, ch, 260, &DefChar, NULL);
                names.push_back(ch);
            }
        } 
        while (::FindNextFile(hFind, &fd));
        ::FindClose(hFind);
    }
    return names;
}

彼得帕克的解决方案,但没有用于:

#include <algorithm>
#include <filesystem>
#include <ranges>
#include <vector>

using namespace std;

int main() {
    vector<filesystem::path> filePaths;
    ranges::transform(filesystem::directory_iterator("."),     
    back_inserter(filePaths), [](const auto& dirFile){return dirFile.path();} );
}

只是我想分享的东西,并感谢您的阅读材料。 玩转 function 以了解它。 你可能会喜欢。 e 代表扩展,p 代表路径,s 代表路径分隔符。

如果传递的路径没有结束分隔符,则分隔符将附加到路径。 对于扩展名,如果输入空字符串,则 function 将返回名称中没有扩展名的任何文件。 如果输入了单个星号,则将返回目录中的所有文件。 如果 e 长度大于 0 但不是单个 *,则如果 e 在零 position 处不包含点,则将在 e 前面添加一个点。

对于返回值。 如果返回零长度 map 则没有找到,但目录打开正常。 如果索引 999 可从返回值获得,但 map 大小仅为 1,则意味着打开目录路径时出现问题。

请注意,为了提高效率,这个 function 可以分成 3 个更小的函数。 最重要的是,您可以创建一个调用程序 function,它将根据输入检测它将调用哪个 function。 为什么这样更有效率? 说如果你要抓取文件的所有内容,那么执行该方法为抓取所有文件而构建的子函数只会抓取所有文件,并且每次找到文件时都不需要评估任何其他不必要的条件。

这也适用于您抓取没有扩展名的文件时。 一个特定的构建 function 仅在找到的 object 是一个文件时才评估天气,然后判断文件名中是否有一个点。

如果您只读取文件不多的目录,则节省可能不多。 但是,如果您正在阅读大量目录,或者该目录有几十万个文件,则可能会节省大量资金。

#include <stdio.h>
#include <sys/stat.h>
#include <iostream>
#include <dirent.h>
#include <map>

std::map<int, std::string> getFile(std::string p, std::string e = "", unsigned char s = '/'){
    if ( p.size() > 0 ){
        if (p.back() != s) p += s;
    }
    if ( e.size() > 0 ){
        if ( e.at(0) != '.' && !(e.size() == 1 && e.at(0) == '*') ) e = "." + e;
    }

    DIR *dir;
    struct dirent *ent;
    struct stat sb;
    std::map<int, std::string> r = {{999, "FAILED"}};
    std::string temp;
    int f = 0;
    bool fd;

    if ( (dir = opendir(p.c_str())) != NULL ){
        r.erase (999);
        while ((ent = readdir (dir)) != NULL){
            temp = ent->d_name;
            fd = temp.find(".") != std::string::npos? true : false;
            temp = p + temp;

            if (stat(temp.c_str(), &sb) == 0 && S_ISREG(sb.st_mode)){
                if ( e.size() == 1 && e.at(0) == '*' ){
                    r[f] = temp;
                    f++;
                } else {
                    if (e.size() == 0){
                        if ( fd == false ){
                            r[f] = temp;
                            f++;
                        }
                        continue;
                    }

                    if (e.size() > temp.size()) continue;

                    if ( temp.substr(temp.size() - e.size()) == e ){
                        r[f] = temp;
                        f++;
                    }
                }
            }
        }

        closedir(dir);
        return r;
    } else {
        return r;
    }
}

void printMap(auto &m){
    for (const auto &p : m) {
        std::cout << "m[" << p.first << "] = " << p.second << std::endl;
    }
}

int main(){
    std::map<int, std::string> k = getFile("./", "");
    printMap(k);
    return 0;
}
#include<iostream>
#include <dirent.h>
using namespace std;
char ROOT[]={'.'};

void listfiles(char* path){
    DIR * dirp = opendir(path);
    dirent * dp;
    while ( (dp = readdir(dirp)) !=NULL ) {
         cout << dp->d_name << " size " << dp->d_reclen<<std::endl;
    }
    (void)closedir(dirp);
}

int main(int argc, char **argv)
{
    char* path;
    if (argc>1) path=argv[1]; else path=ROOT;

    cout<<"list files in ["<<path<<"]"<<std::endl;
    listfiles(path);

    return 0;
}

dirent.h尝试scandir()

man scandir()

根据上面的答案

#include <vector>
#include <string>
#include <algorithm>

#ifdef _WIN32
#include <windows.h>
std::vector<std::string> files_in_directory(std::string path)
{
    std::vector<std::string> files;

    // check directory exists
    char fullpath[MAX_PATH];
    GetFullPathName(path.c_str(), MAX_PATH, fullpath, 0);
    std::string fp(fullpath);
    if (GetFileAttributes(fp.c_str()) != FILE_ATTRIBUTE_DIRECTORY)
        return files;

    // get file names
    WIN32_FIND_DATA findfiledata;
    HANDLE hFind = FindFirstFile((LPCSTR)(fp + "\\*").c_str(), &findfiledata);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        do 
        {
            files.push_back(findfiledata.cFileName);
        } 
        while (FindNextFile(hFind, &findfiledata));
        FindClose(hFind);
    }

    // delete current and parent directories
    files.erase(std::find(files.begin(), files.end(), "."));
    files.erase(std::find(files.begin(), files.end(), ".."));

    // sort in alphabetical order
    std::sort(files.begin(), files.end());

    return files;
}
#else
#include <dirent.h>
std::vector<std::string> files_in_directory(std::string directory)
{
    std::vector<std::string> files;

    // open directory
    DIR *dir;
    dir = opendir(directory.c_str());
    if (dir == NULL)
        return files;

    // get file names
    struct dirent *ent;
    while ((ent = readdir(dir)) != NULL)
        files.push_back(ent->d_name);
    closedir(dir);

    // delete current and parent directories
    files.erase(std::find(files.begin(), files.end(), "."));
    files.erase(std::find(files.begin(), files.end(), ".."));

    // sort in alphabetical order
    std::sort(files.begin(), files.end());

    return files;
}
#endif  // _WIN32

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 键,我们还通过子目录 go。 system("dir /n /b /s * > file_names.txt");

只需在 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;
}

希望这可以帮助!

这对我有用。 它写入一个仅包含所有文件名称(无路径)的文件。 然后它会读取该 txt 文件并为您打印。

void DisplayFolderContent()
    {

        system("dir /n /b * > file_names.txt");
        char ch;
        std::fstream myStream("file_names.txt", std::fstream::in);
        while (myStream.get(ch))
        {
            std::cout << ch;
        }

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM