在 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
获取符号链接所指向的目标,并将其打印出来。