readdir
是一個用于讀取目錄內容的函數,通常在 C 語言中使用。它會返回目錄中的下一個條目(文件或子目錄)。要處理不同類型的文件,你需要檢查每個條目的類型。這可以通過使用 stat
函數來實現。
以下是一個簡單的示例,展示了如何使用 readdir
和 stat
函數來處理目錄中的不同文件類型:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
dir = opendir("."); // 打開當前目錄
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
// 跳過當前目錄和上級目錄的特殊條目
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 使用 stat 函數獲取文件信息
if (stat(entry->d_name, &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 (pipe): %s\n", entry->d_name);
} else if (S_ISSOCK(file_stat.st_mode)) {
printf("Socket: %s\n", entry->d_name);
} else {
printf("Unknown file type: %s\n", entry->d_name);
}
}
closedir(dir);
return EXIT_SUCCESS;
}
這個示例程序會打開當前目錄,然后使用 readdir
函數讀取目錄中的每個條目。對于每個條目,它使用 stat
函數獲取文件信息,然后檢查文件類型。根據文件類型,它會打印相應的消息。