[英]Reading data from a file into an array - C language
I have created a file data.txt
which is to contain the data necessary for future calculations. 我创建了一个文件
data.txt
,其中包含将来计算所需的数据。 I want to write a program that loads all of these data into an array. 我想编写一个程序,将所有这些数据加载到数组中。 Here is my Minimal Example:
这是我的最小示例:
#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: data.txt:
1
2
3
4432
62
435
234
564
3423
74
4234
243
345
123
3
Output: 输出:
171051569
875825715
906637875
859048498
858917429
909445684
875760180
923415346
842271284
839529523
856306484
822752564
856306482
10
4195520
Could you tell me what can have gone wrong? 你能告诉我什么地方出了问题吗?
I suggest for a basic example to use fscanf
. 我建议使用
fscanf
作为一个基本示例。 Later, it might be better to move on to using fgets
and sscanf
. 稍后,最好继续使用
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;
}
Program output: 程序输出:
1 2 3 4432 62 435 234 564 3423 74 4234 243 345 123 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.