C - 列出当前目录中的所有文件,然后移动到上面的目录,列出文件,依此类推,直到到达根目录

标签 c linux

你能帮我开发一个C语言程序来扫描当前目录并 显示位于该处的所有文件的名称 带有扩展名。然后程序转到 父目录,然后成为当前目录,并且这些 重复以上步骤,直到当前目录不存在 成为根目录。 谢谢。 祝你有美好的一天。

附注对不起。这是我正在尝试工作的代码。它列出当前目录中的所有文件,但不转到父目录。 P.S.S 我的代码列出了当前目录中的文件以及对父目录的更改。等等。它按我的预期工作,但我无法检查当前目录是否为根目录,并获得永恒循环。谢谢。

#include <unistd.h>
#include <dirent.h>
#include <stdio.h>
#include <errno.h>

int main(void)
{
  DIR *d;
  char cwd[1024];
  struct dirent *dir;
  do {
      d = opendir(".");
       if (getcwd(cwd, sizeof(cwd)) != NULL)
           fprintf(stdout, "Current working dir: %s\n", cwd);
       else
           perror("getcwd() error");
      if (d)
      {
        while ((dir = readdir(d)) != NULL)
        {
          if (dir->d_type == DT_REG)
          {
            printf("%s\n", dir->d_name);
          }
        }
        chdir("..");
        closedir(d);
      }
  // Do not know how to check if current directory is root
  // and getting eternal loop 
  }while (cwd != "/");
  return 0;
}

输出:

Current working dir: /
Current working dir: /
......................
Current working dir: /

最佳答案

您的 cwd[1] != 0cwd[1] != '\0' 是一种不错的方法。无需将其转换为 int。

您还可以使用strcmp(cwd, "/"),这使得您在做什么更加清楚。在 UNIX 或 Linux 系统的根目录中该值为零。

为了获得更便携的解决方案,您可以将当前目录名称与以前的目录名称进行比较,如下所示:

char cwd[1024];
char parent[1024];
getcwd(cwd, sizeof(cwd));

以及循环内部:

        chdir("..");
        getcwd(parent, sizeof(parent));
        if (strcmp(cwd, parent) == 0)
                break;
        strcpy(cwd, parent);

在 POSIX 系统上,您可以在不使用 getcwd() 的情况下检查当前目录是否为根目录,使用如下代码:

int cwd_is_root(void)
{
        struct stat cwd, parent;
        if (stat(".", &cwd) < 0)
                return -1;
        if (stat("..", &parent) < 0)
                return -1;
        return cwd.st_ino == parent.st_ino && cwd.st_dev == parent.st_dev;
}

像您一样使用 getcwd 会更简单、更好,除非您正在编写自己的 libc! getcwd 是 Linux 上的系统调用。

关于C - 列出当前目录中的所有文件,然后移动到上面的目录,列出文件,依此类推,直到到达根目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35455372/

相关文章:

c - 如何找到以 GCC 开头的未闭括号?

Java FileUtils.writeLines 采用 ANSI 格式,换行符为 CR LF

regex - apache/httpd目录路径更改后,如何将部分url从大写字母更改为小写字母

linux - 无法使 bash 脚本从 cloud-init 运行

c++ - 在 perf_event 中设置 cmask/inv

linux - sudo apt-get中的-E是什么意思

在等距投影中将 3D 坐标转换为 2D

c - 如何向字符串添加值?

c - C 的 Doxygen 输出

c - lua中如何实现接口(interface)?