gsamaras gsamaras - 1 month ago 5
C Question

How to list first level directories only in C?

In a terminal I can call

ls -d */
. Now I want a program to do that for me, like this:

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>

int main( void )
int status;

char *args[] = { "/bin/ls", "-l", NULL };

if ( fork() == 0 )
execv( args[0], args );
wait( &status );

return 0;

This will
ls -l
everything. However, when I am trying:

char *args[] = { "/bin/ls", "-d", "*/", NULL };

I will get a runtime error:

ls: */: No such file or directory


Just call system. Globs on Unixes are expanded by the shell. system will give you a shell.

You can avoid the whole fork-exec thing by doing the glob(3) yourself:

int ec;
glob_t gbuf;
if(0==(ec=glob("*/", 0, NULL, &gbuf))){
    char **p = gbuf.gl_pathv;
            printf("%s\n", *p++);
   /*handle glob error*/ 

You could pass the results to a spawned ls, but there's hardly a point in doing that.

(If you do want to do fork and exec, you should start with a template that does proper error checking -- each of those calls may fail.)