Reputation:
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?
Upvotes: 7
Views: 10360
Reputation: 16016
If you need to get the contents of a directory from a c 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.
Upvotes: 5
Reputation: 371
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};
Upvotes: 9