【问题标题】:Printing all files within a directory and its subdirectories打印目录及其子目录中的所有文件
【发布时间】: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);
}

【问题讨论】:

  • 是时候学习如何使用调试器了。
  • 其实已经过去了。

标签: c file directory


【解决方案1】:

每个目录都包含一个条目“。”那指向它自己。 您必须确保跳过此条目(以及指向父目录的“..”条目)。

因此,对于您的示例,在该行中添加一个额外的条件

if (S_ISDIR(statInfo.st_mode))

【讨论】:

  • 谢谢。你对我应该如何处理这件事有什么建议吗?
  • 使用带有目录名称的 strcmp() 以确保名称既不是“.”也不是“..”
猜你喜欢
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-08
  • 2020-08-22
  • 1970-01-01
  • 1970-01-01
  • 2011-12-24
相关资源
最近更新 更多