【发布时间】:2017-03-15 20:30:59
【问题描述】:
我的目标是打印目录及其子目录中的所有文件。如果路径是文件,我打印出路径。但是,如果路径是目录,那么我递归调用pathInfo(pathnm),其中pathnm 是路径。我的理由是最终它将到达最后一个目录,在这种情况下它将打印该目录中的所有文件。随着它向最后一个目录前进,它将依次打印出它遇到的文件。最终,将打印给定路径目录及其子目录中的所有文件。
问题是在运行时,程序无法打印文件名。相反,它会打印连续的垃圾行,例如/Users/User1//././././././././././././。这种情况一直持续到程序退出并出现错误progname: Too many open files。
我如何确定我做错了什么,以及如何修复它以使程序按照我描述的方式运行?我是编程新手。
路径信息函数
#include "cfind.h"
void getInfo(char *pathnm, char *argv[])
{
DIR *dirStream; // pointer to a directory stream
struct dirent *dp; // pointer to a dirent structure
char *dirContent = NULL; // the contents of the directory
dirStream = opendir(pathnm); // assign to dirStream the address of pathnm
if (dirStream == NULL)
{
perror(argv[0]);
exit(EXIT_FAILURE);
}
while ((dp = readdir(dirStream)) != NULL) // while readdir() has not reached the end of the directory stream
{
struct stat statInfo; // variable to contain information about the path
asprintf(&dirContent, "%s/%s", pathnm, dp->d_name); // writes the content of the directory to dirContent // asprintf() dynamically allocates memory
fprintf(stdout, "%s\n", dirContent);
if (stat(dirContent, &statInfo) != 0) // if getting file or directory information failed
{
perror(pathnm);
exit(EXIT_FAILURE);
}
else if (aflag == true) // if the option -a was given
{
if (S_ISDIR(statInfo.st_mode)) // if the path is a directory, recursively call getInfo()
{
getInfo(dirContent, &argv[0]);
}
else if(S_ISREG(statInfo.st_mode)) // if the path is a file, print all contents
{
fprintf(stdout, "%s\n", dirContent);
}
else continue;
}
free(dirContent);
}
closedir(dirStream);
}
【问题讨论】:
-
是时候学习如何使用调试器了。
-
其实已经过去了。