在 CentOS 系統中,使用 readdir 函數可以讀取目錄中的文件。為了實現文件過濾,你可以在遍歷目錄時檢查每個文件的屬性,然后根據需要決定是否處理該文件。以下是一個簡單的示例,展示了如何使用 readdir 函數和 dirent.h 庫來實現文件過濾:
#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 file_path[1024];
snprintf(file_path, sizeof(file_path), "%s/%s", argv[1], entry->d_name);
// 獲取文件狀態
if (stat(file_path, &file_stat) == -1) {
perror("stat");
continue;
}
// 過濾條件:僅顯示普通文件
if (S_ISREG(file_stat.st_mode)) {
printf("%s\n", file_path);
}
}
closedir(dir);
return 0;
}
在這個示例中,我們首先打開一個目錄,然后使用 readdir 函數遍歷目錄中的所有文件。對于每個文件,我們使用 stat 函數獲取文件的狀態信息,然后檢查文件類型是否為普通文件(S_ISREG)。如果是普通文件,我們將其路徑打印出來。
你可以根據需要修改過濾條件,例如,你可以檢查文件的擴展名、大小、修改時間等屬性,以便僅顯示符合特定條件的文件。