【发布时间】:2015-06-23 05:50:35
【问题描述】:
我正在尝试获取命令行参数以在 exec 中使用它
但我的代码无法正常工作,因为它返回垃圾作为输出。
(我是 ubuntu 用户)
到目前为止,这是我所做的:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int argc,char *argv[]){
char command[1024];
int i;
fflush(stdin); // i try to empty the buffer
for ( i = 1; i < argc; ++i) {
strcat(command, argv[i]);
strcat(command," ") ; //here i try to copy the arguments
}
printf("%s\n",command);
return 0;
}
编译后在终端的输出是:
ubuntu-gnome@ubuntu-gnome:~/Desktop$ ./1 theo psallidas
����*theo psallidas
【问题讨论】:
-
fflush(stdin);一方面你没有使用stdin,另一方面fflush用于输出流。 -
你没有初始化
command,所以它的内容是垃圾。将argv[1]添加到数组后,其内容为garbage + argv[1]。