读取文件并保存在一个数组中
答
下面是一个例子做了你问什么,错误检查,并动态调整您的阵列更多的数据中读出。
#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
好了,你有什么迄今所做的,什么问题都有你遇到这样做? – 2011-04-06 14:27:28
尝试['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