在 CentOS 系統中,可以使用 readdir
函數來讀取目錄中的文件和子目錄。為了判斷文件類型,你可以使用 stat
函數來獲取文件的元數據,然后根據文件類型標志進行判斷。
以下是一個簡單的示例,展示了如何使用 readdir
和 stat
函數來判斷文件類型:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
if (argc != 2) {
fprintf(stderr, "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;
}
// 獲取文件的元數據
if (stat(entry->d_name, &file_stat) == -1) {
perror("stat");
closedir(dir);
return 1;
}
// 判斷文件類型
switch (file_stat.st_mode & S_IFMT) {
case S_IFREG:
printf("%s is a regular file\n", entry->d_name);
break;
case S_IFDIR:
printf("%s is a directory\n", entry->d_name);
break;
case S_IFCHR:
printf("%s is a character device\n", entry->d_name);
break;
case S_IFBLK:
printf("%s is a block device\n", entry->d_name);
break;
case S_IFIFO:
printf("%s is a FIFO (named pipe)\n", entry->d_name);
break;
case S_IFSOCK:
printf("%s is a socket\n", entry->d_name);
break;
default:
printf("%s is of unknown type\n", entry->d_name);
break;
}
}
closedir(dir);
return 0;
}
編譯并運行這個程序,傳入一個目錄作為參數,它將輸出該目錄中每個文件的類型。注意,這個程序只檢查了常見的文件類型,還有其他類型可能沒有被涵蓋。你可以根據需要擴展 switch
語句來處理其他類型。