我尝试编写程序,其中一部分列出了所有目录(尤其是从/开始),但我遇到了/proc/self 的问题,它是无限递归的(我得到/proc/self/task/4300/fd/3/proc/self/task/4300/fd/3/proc/self/task/4300/fd/3/proc/...等等)。有什么好的处理方法?
编辑:程序是用 C 语言编写的,我使用 opendir()、readdir()
最佳答案
您可以使用 S_ISLNK macro to test the st_mode field通过调用 lstat 返回。如果文件是符号链接(symbolic link),请不要尝试跟随它。
[user@machine:~]:./list | grep link
/proc/mounts is a symbolic link
/proc/self is a symbolic link
示例代码
#include <stdio.h> // For perror
#include <stdlib.h>
#include <sys/types.h> // For stat, opendir, readdir
#include <sys/stat.h> // For stat
#include <unistd.h> // For stat
#include <dirent.h> // For opendir, readdir
const char *prefix = "/proc";
int main(void)
{
DIR *dir;
struct dirent *entry;
int result;
struct stat status;
char path[PATH_MAX];
dir = opendir(prefix);
if (!dir)
{
perror("opendir");
exit(1);
}
entry = readdir(dir);
while (entry)
{
result = snprintf(path, sizeof(path), "%s", prefix);
snprintf(&path[result], sizeof(path) - result, "/%s", entry->d_name);
printf("%s", path);
result = lstat(path, &status);
if (-1 == result)
{
printf("\n");
perror("stat");
exit(2);
}
if (S_ISLNK(status.st_mode))
{
printf("%s", " is a symbolic link");
}
printf("\n");
entry = readdir(dir);
}
return(0);
}
关于c - 在 linux 中列出目录时的无限递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4740818/