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
网友评论