[英]Reading data from a file into an array - C language
我创建了一个文件data.txt
,其中包含将来计算所需的数据。 我想编写一个程序,将所有这些数据加载到数组中。 这是我的最小示例:
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
int main(void) {
FILE *fp = fopen("data.txt", "r");
int array[15];
fread(array, sizeof(int), 15, fp);
for(int i = 0; i < 15; i++) {
printf("%d \n", array[i]);
}
}
data.txt:
1
2
3
4432
62
435
234
564
3423
74
4234
243
345
123
3
输出:
171051569
875825715
906637875
859048498
858917429
909445684
875760180
923415346
842271284
839529523
856306484
822752564
856306482
10
4195520
你能告诉我什么地方出了问题吗?
我建议使用fscanf
作为一个基本示例。 稍后,最好继续使用fgets
和sscanf
。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("data.txt", "r");
if(fp == NULL) {
exit(1);
}
int num;
while(fscanf(fp, "%d", &num) == 1) {
printf("%d\n", num);
}
fclose(fp);
return 0;
}
程序输出:
1 2 3 4432 62 435 234 564 3423 74 4234 243 345 123 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.