在 Linux 中,opendir()
函數用于打開一個目錄流,但它本身并不提供直接按文件類型篩選的功能。要實現按文件類型篩選目錄內容,你需要結合使用 readdir()
函數和文件屬性檢查函數(如 stat()
)。以下是一個簡單的示例,展示如何使用 C 語言編寫一個程序,按文件類型篩選目錄內容:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <directory_path>\n", argv[0]);
return 1;
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
struct stat file_stat;
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", argv[1], entry->d_name);
if (stat(full_path, &file_stat) == -1) {
perror("stat");
continue;
}
// 檢查文件類型
if (S_ISREG(file_stat.st_mode)) {
printf("Regular file: %s\n", entry->d_name);
} else if (S_ISDIR(file_stat.st_mode)) {
printf("Directory: %s\n", entry->d_name);
} else if (S_ISCHR(file_stat.st_mode)) {
printf("Character device: %s\n", entry->d_name);
} else if (S_ISBLK(file_stat.st_mode)) {
printf("Block device: %s\n", entry->d_name);
} else if (S_ISFIFO(file_stat.st_mode)) {
printf("FIFO: %s\n", entry->d_name);
} else if (S_ISSOCK(file_stat.st_mode)) {
printf("Socket: %s\n", entry->d_name);
} else {
printf("Other: %s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
這個程序接受一個目錄路徑作為命令行參數,然后打開該目錄并讀取其內容。對于每個目錄項,它使用 stat()
函數獲取文件屬性,并根據文件類型打印相應的消息。
要編譯這個程序,請將其保存為 list_files_by_type.c
,然后運行以下命令:
gcc -o list_files_by_type list_files_by_type.c
現在你可以使用這個程序按文件類型篩選目錄內容,例如:
./list_files_by_type /path/to/directory
這將顯示指定目錄中所有文件的類型。