0

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?

3
  • That is a text file, not a binary. Print your result in hex and you'll see it has read the characters. Commented Feb 11, 2018 at 20:24
  • 3
    fread reads a fixed size of data which does not suit a text file which has variable length data. I suggest you explore fgets and sscanf functions. Commented Feb 11, 2018 at 20:25
  • 1
    If you copy-paste your question title, verbatim, into the search box of your favorite search engine, I'm sure you will get thousands of duplicates here on stackoverflow.com. Commented Feb 11, 2018 at 20:25

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.