美文网首页
C++读一个目录下所有文件的方法

C++读一个目录下所有文件的方法

作者: louyang | 来源:发表于2020-01-06 10:26 被阅读0次
C++ 17
#include <string>
#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    std::string path = "/file/path";
    for (const auto & entry : fs::directory_iterator(path))
        std::cout << entry.path() << std::endl;
}
$ g++ a.cpp -std=c++17 -lstdc++fs && ./a.out
C++ 17 前
#include <stdio.h>
#include <dirent.h>

int main()
{
    DIR *dir;
    struct dirent *ent;

    if ((dir = opendir ("/file/path")))
    {
        /* print all the files and directories within directory */
        while ((ent = readdir (dir)))
            printf ("%s\n", ent->d_name);
        closedir (dir);
        return 0;
    }
    else
    {
        /* could not open directory */
        perror ("");
        return -1;
    }
}
$ g++ b.cpp && ./a.out
参考

https://stackoverflow.com/questions/612097/how-can-i-get-the-list-of-files-in-a-directory-using-c-or-c
https://stackoverflow.com/questions/33149878/experimentalfilesystem-linker-error

相关文章

网友评论

      本文标题:C++读一个目录下所有文件的方法

      本文链接:https://www.haomeiwen.com/subject/icazoctx.html