readdir 是一個用于讀取目錄內容的函數,它本身并不提供直接的文件過濾功能。但是,你可以通過在讀取目錄內容后對每個文件進行檢查來實現文件過濾。以下是一個使用 readdir 和 opendir 在 C 語言中實現文件過濾功能的示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
int is_directory(const char *path) {
struct stat path_stat;
if (stat(path, &path_stat) != 0) {
return 0;
}
return S_ISDIR(path_stat.st_mode);
}
void list_files_with_extension(const char *directory, const char *extension) {
DIR *dir = opendir(directory);
if (dir == NULL) {
perror("opendir");
return;
}
struct dirent *entry;
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", directory, entry->d_name);
// 檢查文件擴展名
if (strstr(entry->d_name, extension) != NULL) {
printf("%s\n", file_path);
}
}
closedir(dir);
}
int main() {
const char *directory = "/path/to/your/directory";
const char *extension = ".txt";
list_files_with_extension(directory, extension);
return 0;
}
在這個示例中,我們定義了一個名為 list_files_with_extension 的函數,它接受一個目錄路徑和一個文件擴展名作為參數。該函數首先使用 opendir 打開目錄,然后使用 readdir 讀取目錄中的每個條目。對于每個條目,我們檢查它是否是一個目錄(使用 is_directory 函數),然后檢查它的擴展名是否與給定的擴展名匹配。如果匹配,我們將文件的完整路徑打印出來。
在 main 函數中,我們調用 list_files_with_extension 函數,傳入要搜索的目錄路徑和要過濾的文件擴展名。這個示例將打印出指定目錄中所有具有給定擴展名的文件的完整路徑。