如何使用 C/C++ 獲取目錄中檔案列表?
C++ 標準中沒有提供此類方法。可以使用 system 命令初始化 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.o drwxrwxrwx 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 顯示列表。
示例
可以使用 direct 程式包(https://github.com/tronkko/dirent) 以使用一個更加靈活的 API。可以按如下方式使用該 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.out hello.cpp hello.py hello.o hydeout my_file.txt watch.py
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP