【发布时间】:2017-04-28 06:44:34
【问题描述】:
好的,我需要编写一个 C 程序来处理和比较命令行参数。例如,假设程序名为 test.c。我是这样执行的:./test load something store one two load store ...等。我的意思是当有一个“load”命令时,它会解析 argc+1 并用它做一些事情,而当有一个“store”命令时,它是打算做其他事情并解析 argc+1 和 argc+2。 到目前为止,这是我的方法:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Tooks {
char s1[50];
char s2[50];
char s3[50];
} Test; /*use this struct to compare the command line arguments in
which in am interested at every time. */
int main (int argc, char *argv){
int num = argc;
int y,i;
char args[num][50]; /*use this num-places array with each string
containing 50 chars. I did that because if i try directly to
strcpy( test.s1, argv[i]) i would get a seg fault. */
Test test;
strcpy( test.s1, "null");
strcpy( test.s2, "null");
strcpy( test.s3, "null");
for (y=0; y<num; y++){
strcpy(args[y], "null");
}//"initializing" the array as null
for (i=1; i<num;){
//copy the 3 command line arguments.
strcpy( test.s1, args[i]);
strcpy( test.s2, args[i+1]);
strcpy( test.s3, args[i+2]);
printf("s1 %s, s2 %s, s3 %s, num %d\n", test.s1, test.s2, test.s3, num);//Just a test print
if (strcmp(test.s1, "store")==0 && strcmp(test.s2, "null") != 0 && strcmp(test.s3, "null") != 0){
printf("%s\n, %s\n", test.s2, test.s3);
i=i+3;
}
else if (strcmp(test.s1, "load")==0 && strcmp(test.s2, "null") != 0){
printf("%s\n", test.s2);
i=i+2;
}
else {
printf("nothing\n");
printf("s1 %s, s2 %s, s3 %s\n", test.s1, test.s2, test.s3);
i++;
}
}
printf("end %d\n", argc);
return 0;
}
这是输出:
s1 null, s2 null, s3 null, num 6
nothing
s1 null, s2 null, s3 null
s1 null, s2 null, s3 null, num 6
nothing
s1 null, s2 null, s3 null
s1 null, s2 null, s3 null, num 6
nothing
s1 null, s2 null, s3 null
s1 null, s2 null, s3 �, num 6
nothing
s1 null, s2 null, s3 �
s1 null, s2 �, s3 , num 6
nothing
s1 null, s2 �, s3
end 6
对于命令 ./test load something store 一二
似乎命令行参数既没有传递给结构也没有传递给数组。 有任何想法吗? :)
【问题讨论】:
-
您实际上从未使用过
argv,因此您无法获得命令行参数。 -
为什么 num/argc 是 6?
-
如果没有参数会怎样?
argv[0]指的是可执行文件名本身。您并没有真正将参数传递给应用程序本身 -
非常增加循环控制变量
i的奇怪方式。在该循环中,三个strcpy语句中的一些语句将破坏args数组。 -
...例如
args[i+2]在最后一次迭代中i == num-1将是args[num+1],这显然超出了数组边界。