you could use the system command:
system("ls *.txt");
to let the shell do the globbing for you.
题
I'm having issues execvping the *.txt wildcard, and reading this thread - exec() any command in C - indicates that it's difficult because of "globbing" issues. Is there any easy way to get around this?
Here's what I'm trying to do:
char * array[] = {"ls", "*.txt", (char *) NULL };
execvp("ls", array);
解决方案
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:
fnmatch()
to match file name with a shell-like wildcard pattern.vfork()
and one of the exec(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!