2011-04-06 53 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中做了你想要的。

相关问题