简体   繁体   中英

How can I run 'ls' with options from a C program?

I want to execute the command ls -a using execv() on a Linux machine as follows:

char *const ptr={"/bin/sh","-c","ls","-a" ,NULL};
execv("/bin/sh",ptr);

However, this command does not list hidden files. What am I doing wrong?

I'm not sure why you're passing this via /bin/sh ... but since you are, you need to pass all the arguments after -c as a single value because these are now to be interpreted by /bin/sh .

The example is to compare the shell syntax of

/bin/sh -c ls -a

to

/bin/sh -c 'ls -a'

The second works, but the first doesn't.

So your ptr should be defined as

char * const ptr[]={"/bin/sh","-c","ls -a" ,NULL}; 

If you need to get the contents of a directory from a program, then this is not the best way - you will effectively have to parse the output of ls , which is generally considered a bad idea .

Instead you can use the libc functions opendir() and readdir() to achieve this.

Here is a small example program that will iterate over (and list) all files in the current directory:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <dirent.h>

int main (int argc, char **argv) {
    DIR *dirp;
    struct dirent *dp;

    dirp = opendir(".");
    if (!dirp) {
        perror("opendir()");
        exit(1);
    }

    while ((dp = readdir(dirp))) {
        puts(dp->d_name);
    }

    if (errno) {
        perror("readdir()");
        exit(1);
    }

    return 0;
}

Note the listing will not be sorted, unlike the default ls -a output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM