简体   繁体   中英

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. 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:

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 . Later, it might be better to move on to using fgets and 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM