我正在尝试将文本文件中的行读入 char 数组,但出现了问题。请查看代码,让我知道我做错了什么。谢谢。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i=0,j;
char* string[100];
char line[100];
FILE *file;
file = fopen("patt", "r");
while(fgets(line, sizeof line, file)!=NULL) {
printf("%d %s",i, line);
string[i]=line;
i++;
}
for (j=0 ; j<i ; j++) {
printf("string[%d] %s",j, string[j]);
}
fclose(file);
return 0;
}
输入文件 patt 有以下内容。
rec
cent
ece
ce
recent
nt
在执行上面的代码时,我得到了这个
0 rec
1 cent
2 ece
3 ce
4 recent
5 nt
string[0] nt
string[1] nt
string[2] nt
string[3] nt
string[4] nt
string[5] nt
我期望的是这个
0 rec
1 cent
2 ece
3 ce
4 recent
5 nt
string[0] rec
string[1] cent
string[2] ece
string[3] ce
string[4] recent
string[5] nt