2015-04-07 58 views
0

我有一個讀出功能,但在最後一行重複3次以上C:存儲從.txt文件線成一個二維數組

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 

我似乎無法弄清楚它爲什麼重複第l ast線。謝謝!

+3

因爲你沒有複製行內容,每讀覆蓋它。 –

+0

是否有任何理由需要'numProgs'和'我'?它們似乎被初始化爲相同的值(0),並且兩者同時增加。我知道這並不能解決您的問題,但是您應該降低代碼的複雜性,並且這會使錯誤更容易找到。 – Jestin

回答

2

你應該

programs[i] = strdup(line); 
+0

我試過但是它給了我一個錯誤 – Kara

+0

什麼是錯誤 –

+0

一個警告*:警告:不兼容的隱含聲明內置函數'strdup' – Kara

1

更換

programs[i] = line; 

隨着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); 
相關問題