Program : List all C files in the current folder using execlp() system call:
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("Before Execl\n");
execlp("ls","ls","*.c",NULL); // this should print all c files in the current folder.
return 0;
}
Program output:
Before Execl
ls: cannot access *.c: No such file or directory
Whenever I use ‘*‘ in the search pattern, I am getting a similar kind of error. Please suggest some appropriate solution.
If you want shell metacharacters expanded, invoke the shell to expand them, thus:
Note that if
execl()or any of theexec*functions returned, it failed. You don’t need to test its status; it failed. You should not then doexit(0);(orreturn 0;in themain()function) as that indicates success. It is courteous to include an error message outlining what went wrong, and the message should be written tostderr, notstdout— as shown.You can do the metacharacter expansion yourself; there are functions in the POSIX library to assist (such as
glob()). But it is a whole heap simpler to let the shell do it.(I’ve revised the code above to use
execlp()to conform to the requirements of the question. If I were doing this unconstrained, I’d probably useexecl()and specify"/bin/sh"as the first argument instead.)