How to execvp ls *.txt in C How to execvp ls *.txt in C shell shell

How to execvp ls *.txt in C


you could use the system command:

system("ls *.txt");

to let the shell do the globbing for you.


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:

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!