Search code examples
c++linuxarrayslsoutput

how to get output of ls command to an array in c++


Is there a way to run the linux command ls, from c++, and get all the outputs stored in one array, in c++?

Thanks


Solution

  • If you insist on actually running ls, you can use popen to launch the process and read the output:

    FILE *proc = popen("/bin/ls -al","r");
    char buf[1024];
    while ( !feof(proc) && fgets(buf,sizeof(buf),proc) )
    {
        printf("Line read: %s",buf);
    }
    

    But you could probably better be reading the directory contents and file info yourself, using opendir and readdir.