Simple directory listing in C?

ii silver ii

ǝɹıɟpǝʞɔı&
Dec 18, 2008
767
23
0
I'm passing parameters into a small program in C but need to perform a listing of the current working directory, I've been using quite abit of bash so this was pretty simple with ls.

What's the equivalent to this in C?

So far the only sort of function I can think of is to loop through with something like scandir?

Thanks
 


There is a getcwd function. Don't remember the library.

What's up with this love for C? This is the second thread I am seeing within 5 minutes...
 
Future reference I just used,

Code:
system("ls -l");

Please never use that. 99% of the time the system function is NOT the way to do things.

Code:
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main(int argc, char **argv) {
        DIR *dir;
        struct dirent *de;

        dir = opendir(argv[1]);
        if (dir != NULL) {
                while ((de = readdir(dir))) {
                        puts(de->d_name);
                }
                closedir(dir);
        }
        return 0;
}

Now gcc -Wall -o list list.c to compile provided you copied the code into a file called list.c then type ./list <dir to list>

if you want to list the current directory ./list ./
 
Yeh I know the system way is not the correct way but I only needed it to prove something, thanks for this other way though a good reference.