2014-10-22 127 views
0

我試圖將c文件的每一行添加到數組中。 files.txt的內容是從c文件讀取行並將字符串放入數組

first.c 
second.c 
third.c 
fourth.c 

我想我的代碼打印每行的內容,行添加到我的數組,然後打印出我的陣列中的每個條目。現在它正確地完成了第一部分,但它只是將第四個c添加到數組中。有人能告訴我我的代碼有什麼問題嗎?

#include <stdio.h> 
#include <stdlib.h> 

int main(void) { 
    int i=0; 
    int numProgs=0; 
    char* programs[50]; 
    char line[50]; 

    FILE *file; 
    file = fopen("files.txt", "r"); 

    while(fgets(line, sizeof line, file)!=NULL) { 
     //check to be sure reading correctly 
     printf("%s", line); 
     //add each filename into array of programs 
     programs[i]=line; 
     i++; 
     //count number of programs in file 
     numProgs++; 
    } 

    //check to be sure going into array correctly 
    for (int j=0 ; j<numProgs+1; j++) { 
     printf("\n%s", programs[j]); 
    } 

    fclose(file); 
    return 0; 
} 
+0

沒有ü意味着'的sizeof(線)'? – CinCout 2014-10-22 07:26:37

+0

@gargankit'sizeof line'也是正確的。 – 2014-10-22 07:32:09

+0

這一行:programs [i] = line;將不會有兩個原因。 1)對於char指針的50個指針的數組需要爲這50個指針中的每一個指針分配內存(並設置指向該內存的指針)。建議您使用calloc(),這樣內存段將被預先設置爲全部'\ 0'。 2)所有這一行正在做的是將程序[i]指針設置爲指向數組行[]。真正需要的是類似於:strcpy(programs [i],line); – user3629249 2014-10-22 09:01:47

回答

0

您需要更改

programs[i]=line; 

programs[i]=strdup(line); 

否則programs陣列中的所有指針將指向同一位置(即line)。

順便說一句:如果files.txt包含超過50行,您將遇到麻煩。

0

你需要爲每個行分配新的存儲,否則你只有1個線緩衝存儲文件的名稱,以便只有最後一次顯示了,在while循環中做到這一點:

programs[i] = calloc(strlen(line)+1, 1); 
strcpy(programs[i], line); 
0
  1. 那裏不需要i並且保存所有指向數組中行的指針,您必須使用strdup()。只要做到這樣:

    programs[numProgs++] = strdup(line);

  2. 在第二循環條件必須是j < numProgs

  3. 添加附加條件while循環,以防止寫入傳遞數組的末尾:

    while(fgets(line, sizeof line, file)!=NULL && numProgs < 50)

0
聲明 char *programs[50]

是無效的指針。所以你根據每一行的大小爲每個指針分配內存。所以,試試這個。(我在這裏使用malloc &的strcpy)

#include <stdio.h> 
    #include <stdlib.h> 
    #include<string.h> 

    int main(void) { 
    int i=0; 
    int numProgs=0; 
    char* programs[50]; 
    char line[50]; 

    FILE *file; 
    file = fopen("files.txt", "r"); 

    while(fgets(line, sizeof line, file)!=NULL) { 
    //check to be sure reading correctly 
    printf("%s", line); 
    //add each filename into array of programs 
    programs[i]=malloc(sizeof(line)); 
    strcpy(programs[i],line); 
    i++; 
    //count number of programs in file 
    numProgs++; 
    } 

    //check to be sure going into array correctly 
    for (int j=0 ; j<numProgs+1; j++) { 
    printf("\n%s", programs[j]); 
} 

fclose(file); 
return 0; 
} 
相關問題