0

I am coding an algorithm that takes a file from the command prompt and stock its numbers into an array.

The file looks like this:

12 563 898 521

And here is the code:

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

//  CODE

void howto(const char *) ;

int main(int k, const char *argv[])
{   if (k < 2) howto(*argv) ;
    int i = 0, array[2500] ;
    FILE * R = fopen(argv[1], "r") ;

    // pass file content to array
    if (! R) return 1 ;
    while (!feof(R)) {
        fscanf(R, "%d ", &array[i]) ;
        i++ ; }
    fclose(R) ;
    for(int x = 0 ; x < i ; x++ ) {
        printf("lol : %d\n", array[x]) ; }
    return 0 ; }

void howto(const char *P) {printf("Expected: %s <file to read>\n", P) ; }

The code run without warnings but has no result: it sorts of run forever. I am guessing my issue comes to my while loop, but I have not been coding in C for a while and I have no idea why the syntax is not having the intended effect. Any ideas?

Thank you!

1 Answers1

1

Read manual page of fscanf & Check the return value. man 3 fscanf says

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure

Replace

while (!feof(R)) {
      fscanf(R, "%d ", &array[i]) ;
      i++ ; 
}

with

while (i < 2500 && fscanf(R, "%d ", &array[i]) == 1) { /*return 1 if read one item */
      i++ ;
}

Also read Why is “while ( !feof (file) )” always wrong?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Achal
  • 11,821
  • 2
  • 15
  • 37
  • I was sure it came from that while! Thank you so much for the in-depth answer to read too. Solved my issue and told me why I had it in the first place ;). – Joanny Rouviere Apr 27 '18 at 14:17