在 Ubuntu 中,readdir
函数用于读取目录的内容
以下是一个简单的示例,展示了如何在 C 语言中使用 readdir
函数处理符号链接:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
struct stat statbuf;
if (lstat(path, &statbuf) == -1) {
perror("lstat");
continue;
}
if (S_ISLNK(statbuf.st_mode)) {
printf("Symbolic link: %s\n", entry->d_name);
} else {
printf("Regular file or directory: %s\n", entry->d_name);
}
}
closedir(dir);
return EXIT_SUCCESS;
}
在这个示例中,我们首先使用 opendir
打开一个目录,然后使用 readdir
逐个读取目录中的条目。对于每个条目,我们使用 lstat
函数获取其状态信息,而不是 stat
函数。lstat
函数会返回符号链接本身的信息,而不是它指向的文件的信息。然后,我们使用 S_ISLNK
宏检查条目是否为符号链接。
编译并运行此程序,它将输出目录中每个条目的类型(常规文件、目录或符号链接)。