在 Windows 上讀目錄通常用 FindFirstFile 系列 API,到了 Linux 則要換成 opendir / readdir 這套 POSIX 介面。以下是在 Ubuntu 上取得指定目錄檔名的完整實作。
#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <vector>
#include <string.h>
using namespace std;
void GetFileNames(string path, vector<string>& filenames) {
DIR *pDir;
struct dirent* ptr;
if (!(pDir = opendir(path.c_str()))) return;
while ((ptr = readdir(pDir)) != 0) {
if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0)
filenames.push_back(path + "/" + ptr->d_name);
}
closedir(pDir);
}
int main() {
vector<string> file_name;
string path = "/home/image";
GetFileNames(path, file_name);
for (int i = 0; i < file_name.size(); i++)
cout << file_name[i] << endl;
return 0;
}
整個流程只有三步:打開目錄、逐項讀取、關閉目錄,分別對應 opendir()、readdir()、closedir()。需要的標頭檔是 <sys/types.h> 與 <dirent.h>。
DIR *opendir(const char *pathname);
成功回傳 DIR 指標,失敗回傳 NULL。
struct dirent *readdir(DIR *pDir);
回傳 dirent 結構指標,讀到目錄結尾或出錯時回傳 NULL。
struct dirent {
__ino_t d_ino; // inode 索引節點號
__off_t d_off; // 在目錄檔中的偏移
unsigned short int d_reclen;// 該筆記錄長度
unsigned char d_type; // 檔案類型
char d_name[256]; // 檔名,以 null 結尾
};
實務上最常用的是 d_name(檔名)與 d_type(類型)。d_type 可能的取值:
DT_UNKNOWN = 0 DT_FIFO = 1 DT_CHR = 2 DT_DIR = 4 DT_BLK = 6 DT_REG = 8 DT_LNK = 10 DT_SOCK = 12 DT_WHT = 14
也就是「未知、管線、字元裝置、目錄、區塊裝置、一般檔案、連結、socket」。
最後關閉目錄:
int closedir(DIR *pDir);
成功回傳 0,失敗回傳 -1。實務上別忘了在 while 迴圈中排除 . 與 .. 這兩個由系統自動產生的項目,否則輸出的清單會多出兩筆幽靈檔名。