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.

JavaScript

The output:

JavaScript

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:

JavaScript

and inside the loop:

JavaScript

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

JavaScript

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