您好,我编写了一个程序来执行文本文件中的命令。下面的代码用于首先将一行一行地存储到char数组中。
所以我希望它能做类似的事情
args[0]= The first line of text file
args[1]= The second line of text file
... and so on
在我的代码中,所有数组都将被最后一个数组覆盖。我不知道为什么。
谁能帮我解决这个问题,并告诉我为什么我的代码可以做到这一点。另外,我需要保留char * args []。因为我以后会在execvp()中使用它。
int main(int argc, const char * av[]) {
FILE *fp;
fp = fopen(av[1],"r");
int n_lines=0;
char in[100],*args[16];
int size=sizeof(in);
while(fgets(in, size, fp)!=NULL){
args[n_lines] = in;
printf("Args[0] is %s\n",args[0]);
n_lines++;
}
printf("Now Args[0] is %s\n",args[0]);
}
输出
zacks-MacBook-Pro:prac2 zack$ ./a.out test
Args[0] is ./addone
Args[0] is ./add
Now Args[0] is ./add
int n_lines=0;
char in[100],*args[16];
int size=sizeof(in);
while(fgets(in, size, fp)!=NULL){
args[n_lines] = in;
printf("Args[0] is %s\n",args[0]);
n_lines++;
}
in
每次迭代都会覆盖的值,您需要保留空间(使用malloc->strcpy
或,strdup
如果可用):
char in[100], *args[16];
while (fgets(in, sizeof in, fp) != NULL) {
args[n_lines] = strdup(in);
...
n_lines++;
}
或使用2D数组(sizeof
需要在中进行调整fgets
):
char in[16][100];
while (fgets(in[n_lines], sizeof in[0], fp) != NULL) {
...
n_lines++;
}
就像@MichaelWalz在评论中指出的那样:如果文件多于16行,则会遇到问题。
改成
while (fgets(in[n_lines], sizeof in[0], fp) != NULL) {
...
if (++n_lines == (sizeof in / sizeof in[0])) break;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句