2011-05-16 20 views
0

我需要讀取一個文件,文件的每一行上都有一個字符串(最多50個字符長),我需要將每行存儲到一個數組中的指針。因此,如果該文件內容如下:需要幫助將文件的內容掃描到指針數組中

1234 
abcd 
5667 
... 

則數組(調用的函數)是*功能[0] = 1234,*功能[1] = ABCD等等...

我已經現在嘗試了一些東西,我似乎無法讓它工作。這是我的代碼的開始,或至少部分屬於我的困惑:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#define MAX_SIZE 201   /* 200 is th emax number of lines in the file*/ 
#define MAX_FUNCTION_LENGTH 51 /* each line is at ax 50 characters long 

main() { 
    char func[MAX_FUNCTION_LENGTH] 
    char * functions[MAX_SIZE]  /* this is my ragged array*/  
    FILE * inf; 
    inf =fopen("list.txt", "r"); 

我已經嘗試了一些東西,但我不能管理,使*函數存儲值正常。有人可以幫我嗎? :)

+2

你嘗試用malloc()初始化嗎? – 2011-05-16 07:19:45

+0

yeha我試過這樣做,問題是我通常只是最終填充每個指針與最後或第一行取決於我使用的方法 – 2011-05-16 08:27:03

回答

1
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#define MAX_SIZE 201 

int main(int argc, char **argv) { 
    FILE *fp = fopen ("D:\\personal\\input.txt","r"); 
    if (!fp) 
     exit (-1); 
    char line [50]; 
    char *functions[MAX_SIZE]; 
    int index = 0; 
    while (!feof(fp)) { 
     fgets (line , 50 , fp); 
     functions[index++] = strdup (line); 
    } 
    fclose (fp); 
    for (int i = 0; i < index; i++) { 
     printf ("[%d] -> [%s]\n", i, functions[i]); 
    } 
    for (int i = 0; i < index; i++) { 
      free (functions[i]); 
} 
} 
+0

'strdup'是非標準的(雖然很簡單,實現)和當數據不再需要時(也就是OP似乎想要避免的),還需要'免費'。 – 2011-05-16 08:01:05

+0

好吧,這是可行的,謝謝。克里斯說,可能需要一些幫助才能解放,我該怎麼做? – 2011-05-16 08:40:29

+0

免費通話更新。 – Avinash 2011-05-16 08:58:12