user3054901
user3054901

Reputation: 377

Read till end of file into array

I've been trying to figure where I'm going wrong but I can't seem to point out where my error is exactly.

I'm trying to read from my text file, these integers

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

into an array A. To make sure it works, I was trying to print A but only getting large random numbers instead. Can someone help me see where i'm going wrong please?

int main(){

FILE* in = fopen("input.txt","r");

int A[100];

while(!feof(in)){
    fscanf(in, "%s", &A);
    printf("%d", A)
  }

 fclose(in);
 return 0;
}

*this is just the main parts of the code related to the question

Upvotes: 0

Views: 2243

Answers (1)

David C. Rankin
David C. Rankin

Reputation: 84551

For all those who actually read why using feof is always wrong, the solution is something similar to the following. The code will open the filename given as the first argument to the program (or read from stdin by default):

#include <stdio.h>

enum { MAXI = 100 };

int main (int argc, char **argv) {

    int i = 0, A[MAXI] = {0};   /* initialize variables */
    /* read from file specified as argument 1 (or stdin, default) */
    FILE *in = argc > 1 ? fopen (argv[1],"r") : stdin;

    if (!in) {  /* validate file opened for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    /* read each number from file or until array full */
    while (i < MAXI && fscanf (in, " %d", &A[i]) == 1)
        printf (" %d", A[i++]);
    putchar ('\n');

    if (in != stdin) fclose (in);

    printf ("\n '%d' numbers read from the file.\n\n", i);

    return 0;
}

Example Use/Output

Using your example values in the file dat/myints.txt results in the following:

$ ./bin/rdints dat/myints.txt
 5 2 4 9 10 1 8 13 12 6 3 7 11

 '13' numbers read from the file.

Upvotes: 1

Related Questions