I wrote a code below
#include<stdio.h>
int main(int argc, char *argv[]) {
char cmd[50]="dir";
if (argc == 2) {
sprintf(cmd,"dir %s",argv[1]);
}
if (argc == 3) {
sprintf(cmd,"dir %s %s", argv[1], argv[2]);
}
printf("%s\n",cmd);
system(cmd);
return 0;
}
when I executed like below
I think can't pass '*' by *argv[]
How can I pass something like "*.c" ?
update
code
#include<stdio.h>
int main(int argc, char *argv[]) {
char cmd[50]="dir";
if (argc == 2) {
sprintf(cmd,"dir %s",argv[1]);
}
if (argc == 3) {
sprintf(cmd,"dir %s %s", argv[1], argv[2]);
}
if (argc > 3) {
sprintf(cmd,"dir %s %s", argv[1], argv[2]);
}
printf("%s\n",cmd);
system(cmd);
return 0;
}
what..... @.@ ?
Updated code again
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[]) {
int i;
char sp[2]=" ", cmd[250]="dir";
if (argc > 1) {
sprintf(cmd,"dir /d ");
for (i =1 ; i < argc; i ++) {
strcat(cmd,sp);
strcat(cmd,argv[i]);
}
}
printf("%s\n",cmd);
system(cmd);
return 0;
}
see what happen when I executed
kind of ugly.... any decent idea?
I'm afraid the accepted answer is not correct as the edit courteously admits. What is happening here is that globbing behaviour is provided in the C runtime but the default behaviour differs between compilers.
Yes, it's a major pain if you do not know what is happening. Worse the globbing does not occur if the glob does not match any files. I was pretty surprised myself.
Under Visual Studio, by default, wildcards are not expanded in command-line arguments. You can enable this feature by linking with setargv.obj or wsetargv.obj:
Under MinGW, by default, wildcards are expanded in command line arguments. To prevent this you can link with CRT_noglob.o or, much more easily, add the global variable:
in your own source in the file which defines main() or WinMain().
This issue is not related to the C runtime, but to the shell behaviour. If you use Windows CMD.EXE, the * is passed unchanged to the programs, whereas if you use Cygwin's
bash
, the shell expands*
to the list of files and passes this expansion as individual arguments to your program. You can prevent this expansion by quoting the wildcards with"*"
or'*'
.Note that you should not use
sprintf
, butsnprintf
to avoid buffer overflows. If you link to the non standard Microsoft C library, you may need to use_snprintf
instead.EDIT: CMD.EXE does not seem to expand wildcards, but the C runtime you link your program with might do it at startup. See this question: Gnuwin32 find.exe expands wildcard before performing search
The solution is to quote the argument.