readdir 函数用于读取目录中的条目。在处理符号链接时,readdir 返回的 d_name 字段包含符号链接指向的目标文件或目录的名称,而不是符号链接本身的名称。这意味着 readdir 不会区分符号链接和普通文件/目录。
如果你需要处理符号链接,可以使用 lstat 函数来获取文件的状态信息,包括是否为符号链接。lstat 函数会返回一个 struct stat 结构体,其中的 st_mode 字段包含了文件的类型信息。你可以使用宏 S_ISLNK 来检查文件是否为符号链接。
下面是一个简单的示例,展示了如何使用 readdir 和 lstat 处理符号链接:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
struct stat statbuf;
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)) {
printf("Symbolic link: %s -> ", entry->d_name);
char target[PATH_MAX];
ssize_t len = readlink(path, target, sizeof(target) - 1);
if (len != -1) {
target[len] = '\0';
printf("%s\n", target);
} else {
perror("readlink");
}
} else {
printf("Regular file or directory: %s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
这个程序接受一个目录作为命令行参数,然后使用 readdir 读取目录中的条目。对于每个条目,它使用 lstat 获取文件状态信息,并检查是否为符号链接。如果是符号链接,它使用 readlink 获取链接指向的目标,并打印出来。