2011-04-06 57 views
0

我想要一個簡單的C程序,它將讀取一個文件並將每行的內容保存到一個數組元素。該文件包含所有整數值。每行只有一個整數值。這樣每個整數值都被存儲在一個數組中。讀取文件並保存在一個數組中

+3

好了,你有什麼迄今所做的,什麼問題都有你遇到這樣做? – 2011-04-06 14:27:28

+0

嘗試['fgets'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fgets.html)和['strtol'](http://pubs.opengroup.org/onlinepubs/9699919799/functions /strtol.html)。 – pmg 2011-04-06 14:38:10

回答

0

下面是一個例子做了你問什麼,錯誤檢查,並動態調整您的陣列更多的數據中讀出。

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

int main(int argc, char ** argv) 
{ 
    char buf[512]; 
    FILE * f; 
    int * array = 0; 
    size_t array_len = 0, count = 0; 

    if (argc != 2) { 
     fprintf(stderr, "Please provide a filename to read\n"); 
     exit(1); 
    } 

    f = fopen(argv[1], "r"); 

    if (f == NULL) { 
     perror("fopen"); 
     exit(1); 
    } 

    while (fgets(&buf[0], 512, f) != 0) { 
     if (count == array_len) { 
      array_len *= 2; 
      if (array_len == 0) { 
       array_len = 32; 
      } 
      array = realloc(array, array_len * sizeof(int)); 
      if (array == NULL) { 
       perror("realloc"); 
       exit(1); 
      } 
     } 
     array[count++] = strtol(buf, 0, 10); 
    } 

    return 0; 
} 
+0

非常感謝....它工作精湛............ – user685875 2011-04-07 07:21:37

0

在這方面有很多網絡資源可以幫助你。一個快速的谷歌搜索pointed me to this example

除了這個例子的非動態性質,它在scanf中做了你想要的。

相關問題