我正在尝试递归遍历目录并打印出所有文件。
当我尝试使用下面的代码执行此操作时,例如,我使用 sprint(".", ".") 调用该函数时,我得到了一堆点的输出。
当我减少允许的打开进程数时 (ulimit -n 20),我得到 17 个点。我不明白,因为我认为 readdir() 和 opendir() 不会创建新进程。这是我的代码:
void sprint(char *filename, char * dirToOpen) {
DIR *directory = opendir(dirToOpen);
struct dirent *entry;
struct stat s;
char pathname[1024];
if (directory) { /*if it's a directory*/
while ((entry = readdir(directory)) != NULL) { /*while there are more entries to read*/
if(strcmp(entry->d_name, filename) == 0) /*if entry name corresponds to filename, print it*/
printf("%s\n", filename);
sprintf(pathname, "./%s", entry->d_name); /*makes pathname*/
if (lstat(pathname, &s) == 0 && S_ISDIR(s.st_mode)) { /*if the file is a directory*/
if(strcmp(entry->d_name, "..") != 0 && strcmp(entry->d_name, ".") != 0) /*if the directory isn't . or ..*/
sprint(filename, entry->d_name);
}
}
closedir(directory);
}
}
此外,它在途中的某个地方没有到达文件的其余部分,因为它只打印点,而不是完整的文件名。我认为它在我最后一个 if 循环中的某个地方,但我不确定。
这是执行此操作的递归代码:
void sprint(char *filename, char * dirToOpen, int level = 0)
{
DIR *dir;
struct dirent *entry;
struct stat s;
if (!(dir = opendir(dirToOpen)))
return;
if (!(entry = readdir(dir)))
return;
do
{
if(lstat(dirToOpen, &s) == 0 && S_ISDIR(s.st_mode)) /*if it's a directory*/
{
char path[1024];
int len = snprintf(path, sizeof(path)-1, "%s/%s", dirToOpen, entry->d_name); /*makes pathname*/
path[len] = 0;
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) /*if the directory isn't . or ..*/
continue;
printf("%*s[%s]\n", level * 2, "", entry->d_name);
sprint(filename ,path, level + 1);
}
else
{
if(strcmp(entry->d_name, filename) == 0 || strcmp(filename, ".") == 0) /*if entry name corresponds to filename, print it*/
printf("%*s- %s\n", 2, "", entry->d_name);
}
} while (entry = readdir(dir)); /*while there are more entries to read*/
closedir(dir);
}
用 sprint(".", ".");
调用它以递归遍历目录并打印出所有文件。
灵感来自 this回答。
我是一名优秀的程序员,十分优秀!