在Linux中,readdir
函數用于讀取目錄中的條目。當你使用readdir
函數時,它會返回一個指向dirent
結構體的指針,該結構體包含了目錄條目的信息,如文件名、文件類型等。要處理文件屬性,你可以使用stat
函數來獲取文件的詳細信息。
以下是一個簡單的示例,展示了如何使用readdir
和stat
函數來處理文件屬性:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
char path[1024];
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;
}
// 構建文件的完整路徑
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
// 獲取文件的詳細信息
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
// 處理文件屬性
printf("File: %s\n", entry->d_name);
printf("Size: %ld bytes\n", file_stat.st_size);
printf("Last modified: %s", ctime(&file_stat.st_mtime));
printf("File type: ");
if (S_ISREG(file_stat.st_mode)) {
printf("Regular file\n");
} else if (S_ISDIR(file_stat.st_mode)) {
printf("Directory\n");
} else if (S_ISCHR(file_stat.st_mode)) {
printf("Character device\n");
} else if (S_ISBLK(file_stat.st_mode)) {
printf("Block device\n");
} else if (S_ISFIFO(file_stat.st_mode)) {
printf("FIFO\n");
} else if (S_ISSOCK(file_stat.st_mode)) {
printf("Socket\n");
} else {
printf("Other\n");
}
}
// 關閉目錄
closedir(dir);
return 0;
}
這個示例程序接受一個目錄作為命令行參數,然后使用readdir
函數讀取目錄中的條目。對于每個條目,它使用stat
函數獲取文件的詳細信息,并根據文件類型打印相應的屬性。