您好,欢迎访问一九零五行业门户网

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

标准 c++ 没有提供执行此操作的方法。您可以使用系统命令来初始化 ls 命令,如下所示 -
示例#include<iostream>int main () { char command[50] = "ls -l"; system(command); return 0;}
输出这将给出输出 -
-rwxrwxrwx 1 root root 9728 feb 25 20:51 a.out-rwxrwxrwx 1 root root 131 feb 25 20:44 hello.cpp-rwxrwxrwx 1 root root 243 sep 7 13:09 hello.py-rwxrwxrwx 1 root root 33198 jan 7 11:42 hello.odrwxrwxrwx 0 root root 512 oct 1 21:40 hydeout-rwxrwxrwx 1 root root 42 oct 21 11:29 my_file.txt-rwxrwxrwx 1 root root 527 oct 21 11:29 watch.py
如果您使用的是 windows,则可以使用 dir 而不是 ls 来显示列表。
示例您可以使用直接包(https://github.com/dir/ls)。 com/tronkko/dirent)以使用更灵活的 api。您可以按如下方式使用它来获取文件列表 -
#include <iostream>#include <dirent.h>#include <sys/types.h>using namespace std;void list_dir(const char *path) { struct dirent *entry; dir *dir = opendir(path); if (dir == null) { return; } while ((entry = readdir(dir)) != null) { cout << entry->d_name << endl; } closedir(dir);}int main() { list_dir("/home/username/documents");}
输出这将给出输出 -
a.outhello.cpphello.pyhello.ohydeoutmy_file.txtwatch.py
以上就是如何使用c/c++获取目录中的文件列表?的详细内容。
其它类似信息

推荐信息