Aemilius
Aemilius

Reputation: 676

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?

Upvotes: 0

Views: 66

Answers (1)

Weather Vane
Weather Vane

Reputation: 34575

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

Upvotes: 2

Related Questions