windows mingw 星号“*"通过 argv[1] 传递给字符串 [英] windows mingw asterisk '*' passing by argv[1] to string
问题描述
我在下面写了一段代码
#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;
}
当我像下面这样执行时
我认为不能通过 *argv[] 传递 '*'
I think can't pass '*' by *argv[]
如何传递类似 "*.c" 的内容?
How can I pass something like "*.c" ?
更新
代码
#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..... @.@ ?
再次更新代码
#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?
推荐答案
这个问题与 C 运行时无关,而是与 shell 行为有关.如果您使用 Windows CMD.EXE,* 会原封不动地传递给程序,而如果您使用 Cygwin 的 bash
,shell 会将 *
扩展到文件列表并传递它扩展作为程序的单独参数.您可以通过用 "*"
或 '*'
引用通配符来防止这种扩展.
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 '*'
.
请注意,您不应该使用 sprintf
,而应使用 snprintf
以避免缓冲区溢出.如果您链接到非标准 Microsoft C 库,则可能需要改用 _snprintf
.
Note that you should not use sprintf
, but snprintf
to avoid buffer overflows. If you link to the non standard Microsoft C library, you may need to use _snprintf
instead.
CMD.EXE 似乎不会扩展通配符,但是您链接程序的 C 运行时可能会在启动时扩展.请参阅此问题:Gnuwin32 find.exe 在执行搜索之前扩展通配符
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
解决方案是引用参数.
这篇关于windows mingw 星号“*"通过 argv[1] 传递给字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!