在Linux系統中,readdir函數用于讀取目錄中的條目。如果你想要實現文件過濾,可以在調用readdir之后對返回的dirent結構體進行判斷和處理。以下是一個簡單的示例,展示了如何使用readdir和opendir函數以及如何實現文件過濾:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
if (argc != 2) {
printf("Usage: %s <directory>\n", argv[0]);
return 1;
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
// 跳過當前目錄(".")和上級目錄("..")
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 拼接完整的文件路徑
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
// 獲取文件的stat信息
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
// 判斷是否為普通文件
if (S_ISREG(file_stat.st_mode)) {
printf("File: %s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
在這個示例中,我們首先檢查命令行參數,確保提供了一個目錄作為輸入。然后,我們使用opendir打開目錄,并使用readdir逐個讀取目錄中的條目。對于每個條目,我們跳過當前目錄(“.”)和上級目錄(“…”)。
接下來,我們使用snprintf拼接完整的文件路徑,并使用stat函數獲取文件的stat信息。通過檢查file_stat.st_mode,我們可以判斷該條目是否為普通文件(S_ISREG宏)。如果是普通文件,我們將其名稱打印出來。
你可以根據需要修改這個示例,以實現更復雜的文件過濾邏輯。例如,你可以檢查文件的擴展名、大小、修改時間等屬性,以決定是否將其包含在結果中。