在linux中列出目录时无限recursion

我尝试写程序,其中部分列出所有目录(尤其是从/开始),但我有一个问题/ proc /自我是无限recursion的(我得到/ proc /自我/任务/ 4300 / fd / 3 / proc / self / task / 4300 / fd / 3 / proc / self / task / 4300 / fd / 3 / proc / …等等)。 什么是处理它的好方法?

编辑:程序是用C语言编写的,我使用opendir(),readdir()

您可以使用S_ISLNK宏来测试对lstat的调用返回的st_mode字段 。 如果文件是一个符号链接,不要试图遵循它。

[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); } 

来自path_resolution(7)

长度限制
   路径名有最大长度。 如果路径名(或解析符号链接时获得的某个中间路径名)太长,则ENAMETOOLONG错误
    (“文件名太长”)。

我认为你应该采取类似的行为:检查太长的路径名。

 #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <sys/param.h> /* Short & sweet recursive directory scan, finds regular files only. Good starting point, should work on Linux OS. Pass the root path, and returns number of dirs and number of files found. */ char *tree_scan( const char *path, int *ndirs, int *nfiles){ DIR *dir; struct dirent *entry; char spath[MAXPATHLEN] = ""; if( !(dir = opendir( path))){ perror("opendir"); exit(1);} for( entry = readdir( dir); entry; entry = readdir( dir)){ sprintf( spath, "%s/%s", path, entry->d_name); if( entry->d_type == DT_REG){ (*nfiles)++; printf( "%s\n", spath);} if( entry->d_type == DT_DIR && (strcmp( ".", entry->d_name)) && (strcmp( "..", entry->d_name))){ (*ndirs)++; tree_scan( spath, ndirs, nfiles); } } closedir( dir); return(0); 

}

/ *像这样调用* /

 int i = 0, l = 0; tree_scan( "/path", &i, &l); printf("Scanned %d directories, %d files.\n", i, l); 

我没有一个* nix终端的方便,但你总是可以看看ls.c的来源,看看它是如何完成的。

作为GNU核心实用程序的一部分的来源可以在这里找到。

几年前我在学校创建了一个ls的克隆,我想我通过观察路径名的大小来解决这个问题。