How to execvp ls *.txt in C
In order to answer this question you have to understand what is going on when you type ls *.txt
in your terminal (emulator). When ls *.txt
command is typed, it is being interpreted by the shell
. The shell
then performs directory listing and matches file names in the directory against *.txt
pattern. Only after all of the above is done, shell
prepares all of the file names as arguments and spawns a new process passing those file names as argv
array to execvp
call.
In order to assemble something like that yourself, look at the following Q/A:
- How to list files in a directory in a C program?
- Use
fnmatch()
to match file name with a shell-like wildcard pattern. - Prepare argument list from matched file names and use
vfork()
and one of theexec(3)
family of functions to run another program.
Alternatively, you can use system()
function as @manu-fatto has suggested. But that function will do a little bit different thing — it will actually run the shell
program that will evaluate ls *.txt
statement which in turn will perform steps similar to one I have described above. It is likely to be less efficient and it may introduce security holes (see manual page for more details, security risk are stated under NOTES section with a suggestion not to use the above function in certain cases).
Hope it helps. Good Luck!