在 CentOS 系統中,readdir 函數用于讀取目錄中的條目。當目錄中包含符號鏈接時,readdir 會返回符號鏈接的名稱,而不是它所指向的目標文件或目錄。如果你想要獲取符號鏈接所指向的目標,你可以使用 lstat 函數來獲取符號鏈接的詳細信息。
以下是一個簡單的示例,展示了如何在 CentOS 中使用 readdir 和 lstat 處理符號鏈接:
#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 statbuf;
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
exit(EXIT_FAILURE);
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != NULL) {
printf("Entry: %s\n", entry->d_name);
// 獲取符號鏈接的詳細信息
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
if (lstat(path, &statbuf) == -1) {
perror("lstat");
continue;
}
// 判斷是否為符號鏈接
if (S_ISLNK(statbuf.st_mode)) {
char target[PATH_MAX];
ssize_t len = readlink(path, target, sizeof(target) - 1);
if (len != -1) {
target[len] = '\0';
printf(" Symbolic link points to: %s\n", target);
} else {
perror("readlink");
}
}
}
closedir(dir);
return 0;
}
這個程序接受一個目錄作為參數,然后使用 readdir 讀取目錄中的條目。對于每個條目,它使用 lstat 獲取詳細信息,并檢查是否為符號鏈接。如果是符號鏈接,它使用 readlink 獲取符號鏈接所指向的目標,并將其打印出來。