C:将.txt文件中的行存储到2d数组中

时间:2015-04-07 00:48:10

标签: c string file-io

我有读取功能,但最后一行重复了3次

 void read()
 {
    FILE *file;
    char line[50];
    int numProgs = 0;
    char* programs[50];
    int i = 0;
    file = fopen("testing.txt", "r");
    while(fgets(line, 50, file) != NULL) {
       printf("%s", line);
       programs[i]=line; 
       i++;
       numProgs++;
     }

    int j = 0;
    for (j=0 ; j<numProgs; j++) {
      printf("\n%s", programs[j]);
    }

     fclose(file);
}

我的testing.txt doc填充了3行(但可以更多)

Jane Smith   123 blue jay st    123-123-3312
John Doe    12 blue st    321-222-1131
Amy White    431 yellow st    +1-23-738-2912

但是当我运行我的读取功能时,它显示了这个

Jane Smith   123 blue jay st    123-123-3312
John Doe    12 blue st    321-222-1131
Amy White    431 yellow st    +1-23-738-2912
Amy White    431 yellow st    +1-23-738-2912
Amy White    431 yellow st    +1-23-738-2912

我似乎无法弄清楚为什么重复最后一行。谢谢!

2 个答案:

答案 0 :(得分:2)

你应该替换

programs[i] = line;

programs[i] = strdup(line);

答案 1 :(得分:1)

strdup为例:

FILE *file;
char line[50];
int numProgs = 0;
char* programs[50];
file = fopen("testing.txt", "r");
while(fgets(line, 50, file) && numProgs < 50) {
    printf("%s", line);
    programs[numProgs++;] = strdup(line);
}

for (int j  =0 ; j < numProgs; j++) {
    printf("\n%s", programs[j]);
    free(programs[j]);
}

fclose(file);
相关问题