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

I want to execute the 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 display hidden files. What am I doing wrong?

+6
source share
2 answers

I'm not sure why you pass this through /bin/sh ... but since you are there, you need to pass all the arguments after -c as a single value, because now they should be interpreted using /bin/sh .

An example is shell syntax comparison.

 /bin/sh -c ls -a 

to

 /bin/sh -c 'ls -a' 

The second works, but the first does not.

So your ptr should be defined as

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

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

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

Here is a small sample 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 that the list will not be sorted, unlike ls -a output by default.

+5
source

All Articles