【问题标题】:Listing directory contents like Unix 'find' command列出目录内容,如 Unix 'find' 命令
【发布时间】:2017-03-04 17:45:55
【问题描述】:

在修改/简化版本的 Unix 'find' 实用程序上工作,当我打印出文件时,我的格式已关闭。

跑步:

./a.out mydir -print

输出应该类似于find,如下:

mydir
mydir/innerDir
mydir/innerDir/innerFile
mydir/testFile

但是,我的输出如下:

mydir/innerDir
innerFile/testFile

这是我拥有的遍历目录内容的函数:

void printdir(char *dir, int depth) {
   DIR *dp;
   struct dirent *entry;
   struct stat statbuf;
   int spaces = depth * 4;
   char *path;

   if((dp = opendir(dir)) == NULL) {
      fprintf(stderr, "Error! Unable to open: %s\n", dir);
      exit(EXIT_FAILURE);
   }

   chdir(dir);
   while((entry = readdir(dp)) != NULL) {
      lstat(entry->d_name, & statbuf);
      if(S_ISDIR(statbuf.st_mode)) {
         if(strcasecmp(".", entry->d_name) == 0 ||
            strcasecmp("..", entry->d_name) == 0)
            continue;
         path = malloc(strlen(dir) + strlen(entry->d_name) + 2);
         strcpy(path, dir);
         strcat(path, "/");
         strcat(path, entry->d_name);
   //         printf("%*s|-- %s/\n", spaces, "", entry->d_name);
        printf("%s\n", path);
        printdir(entry->d_name, depth + 1);
      }
      else
   //         printf("%*s|-- %s\n", spaces, "", entry->d_name);
         printf("%s/", entry->d_name);
   }
   chdir("..");
   closedir(dp);
}

上面的注释行打印出与 Unix 'tree' 实用程序类似的输出。关于如何修改我的打印以获得上面列出的“查找”输出的任何帮助。谢谢!

【问题讨论】:

  • 无需将strcasecmp 与. 一起使用——它的表示不会随大小写而改变。
  • 你说得对,我会改的。
  • 不清楚你在问什么。
  • 无论如何,有两件事 - 最后一个 print 甚至没有添加换行符(它应该,现在它使错误不那么明显了),并检查你正在递归的字符串 (您不应该使用完整路径而不是仅使用最后一个组件进行递归);然后你会注意到你根本不需要chdir...
  • 将我递归使用的字符串从最后一个组件更改为完整路径后,我打印了无法打开目录的错误,因为连接的字符串路径不被视为目录的名称。 (即myDir/innerDir不是目录名,应该就是我遍历的innerDir。

标签: c unix directory find-util


【解决方案1】:

只是递归调用时的一个错误参数,发送完整路径:

printdir(path, depth + 1);

然后对于非目录条目,也打印完整路径:

printf("%s/%s\n", dir, entry->d_name);

----编辑----

在生成完整路径时删除对chdir 的所有调用。

----EDIT-2----

lstat没有在正确的路径上调用,修改为:

 while((entry = readdir(dp)) != NULL) {
     path = malloc(strlen(dir) + strlen(entry->d_name) + 2);
     strcpy(path, dir);
     strcat(path, "/");
     strcat(path, entry->d_name);
     lstat(path, & statbuf);

【讨论】:

  • 在我这样做之后,它会打印 mydir/innerDir,然后在函数顶部打印错误。我删除了对 chdir 的两个调用,然后它打印到它遇到文件的位置,然后它(显然)说无法打开。但是不应该跳到下一个条目吗?
  • 现在它在遇到文件时会打印错误。
  • 作为后续问题,如何使用 strcasecmp 按字典顺序对输出进行排序?
  • 读取给定目录的所有条目,对它们进行排序并做你的技巧(打印/递归)。
猜你喜欢
  • 2018-05-06
  • 2022-06-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 2012-12-09
  • 2012-07-03
  • 2012-12-25
  • 1970-01-01
相关资源
最近更新 更多