您好,我正在编写一个程序来执行文本文件中的命令。下面的代码用于先逐行存入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
or strdup
if available) :
char in[100], *args[16];
while (fgets(in, sizeof in, fp) != NULL) {
args[n_lines] = strdup(in);
...
n_lines++;
}
或者使用二维数组(在fgets
中需要调整sizeof
):
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;
}
关于c - 使用字符指针将文本文件逐行存储到字符数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37023515/