Search code examples
carraysfilelimit

C - Reading Till The EOF, Getting Additional Addresses and Numbers (Array)


So, I have a File full of numbers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

The case is, I don't know the exact number of numbers in this file, so I don't know the exact size of array I will need to write this file info in to this array.

I just gave array much bigger size than I need and I will show you the output, partially it does its job.

Here is the code:

#include <stdio.h>
#include <stdlib.h>

#define ARR_SIZE 30

int main(void){
FILE *fp;
int array[ARR_SIZE];
fp = fopen("C:/project/project.txt", "r");

printf("Numbers: ");

for(int i = 0; i < ARR_SIZE; i++){
    fscanf(fp, "%d", &array[i]);
}
for(int j = 0; j < ARR_SIZE; j++){
    printf("\n%d", array[j]);
}

fclose(fp);
return 0;
}

I am just trying to do standard things, opening file, reading file with for loop, writing all this info to array and outputting array.

Here is the output I get, I understand it is because of the size, but can you tell me how to limit all of these? Easiest way?

Output:

Numbers:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
4199136
0
4200896
6422240
6422296
6422476
1998244384
592257989
-2
1998220218
1998220461
4200896
6422368
4200987
4200896

I have array size 30 and numbers in the file 15, first 15 is okay, it is exactly what I need, but I don't need those number after it...


Solution

  • You need a stop-condition for the loop that reads from the file. One option is to stop when you can't scan an item. Use the return value from fscanf to detect that.

    When you do the printing only print the number of items actual scan'ed.

    Try

    for(int i = 0; i < ARR_SIZE; i++){
        if (fscanf(fp, "%d", &array[i]) != 1) break; // Stop if the scan fails
    }
    for(int j = 0; j < i; j++){  // ARR_SIZE replaced by i
        printf("\n%d", array[j]);  
    }
    

    BTW: You should check that fp is valid just after the file open.