2016-11-02 36 views
1

我的目标是打印目录及其子目录内的所有文件。如果路径是一个文件,我打印出路径。但是,如果路径是目录,那么我递归地调用pathInfo(pathnm),其中pathnm是路径。我的推理是,它最终会到达最后一个目录,在这种情况下,它将打印该目录中的所有文件。随着它朝着最后一个目录前进,它会连续打印遇到的文件。最终,打印给定路径目录及其子目录中的所有文件。打印目录及其子目录中的所有文件

问题是在运行时,程序无法打印文件名。相反,它会打印连续的垃圾线,如/Users/User1//././././././././././././。直到程序退出并出现错误progname: Too many open files

如果我错误地做了什么以及如何修复它,以便程序以我描述的方式运行,我将不胜感激。请以对新编程人员清楚的方式来组织您的答案。

谢谢。

PATHINFO功能

#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); 
} 
+1

它的时间来学习如何使用调试器。 –

+0

它实际上是过去的时间。 –

回答

4

每个目录包含条目 “”这指向自己。 您必须确保跳过此条目(还有指向父目录的“..”条目)。

因此,对于你的榜样,增加额外的条件,行

if (S_ISDIR(statInfo.st_mode)) 
+0

谢谢。你有什么建议,我应该如何去做这件事? –

+2

使用strcmp()作为目录名称,以确保该名称既不是“。”。也不是“..” – neuhaus

+1

非常好。非常感谢您的帮助。 –

相关问题