Skip to content
Advertisement

C – list all files in current directory then move in directory above, list files, and so on until root directory is reached [closed]

Could you help me please to develop a program in C that scans the current directory and displays the names of all files that are located there with extensions. Then program goes to parent directory, which then becomes current, and these above steps are repeated until the current directory is not become root directory. Thanks. Have a nice day.

P.S. Sorry. Here is the code i’m trying to make work. It lists all files from current directory, but do not go to parent directory. P.S.S My code lists files in current directory and changes to parent directory too. And so on. It work as I expect, but I can’t check if current directory is root, and get eternal loop. Thanks.

#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: %sn", cwd);
       else
           perror("getcwd() error");
      if (d)
      {
        while ((dir = readdir(d)) != NULL)
        {
          if (dir->d_type == DT_REG)
          {
            printf("%sn", 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;
}

The output:

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

Advertisement

Answer

Your cwd[1] != 0 or cwd[1] != '' is an okay way to do it. There’s no need to cast that to an int.

You could also use strcmp(cwd, "/"), which makes it slightly more clear what you are doing. This will be zero at the root directory on a UNIX or Linux system.

For a more portable solution, you can compare the current directory name with the previous directory name, something like this:

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

and inside the loop:

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

On a POSIX system, you can check if the current directory is the root without using getcwd(), using code like this:

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;
}

It is simpler and better just to use getcwd as you did, unless you are writing your own libc! getcwd is a system call on Linux.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement