Bourezg
Bourezg

Reputation: 59

How to populate an array with integers from a FILE?

I am completly lost and have no clue how to get the integers from a file to be inputted into an array. if a file looks like:

1 2 3
4 5 6
7 8 9

and I want an array a[9] = {1,2,3,4,5,6,7,8,9} then how do I even go about doing this?

would something along the lines of this work?

int a[9];
int i;

infile = fopen("test.txt","r");
while(fscanf( infile, "%d", *(a+i) != EOF)
{
     fscanf( infile, "%d", *(a+i))
     i++
}

In actuality, I'd like the array to be some arbitrarily large number knowing that the file wont consist of more than that amount, i.e. 1000.

Upvotes: 0

Views: 128

Answers (2)

Fiddling Bits
Fiddling Bits

Reputation: 8861

Why do you include this line twice?

fscanf(infile, "%d", *(a+i));

Once as a condition and once in the body of the loop? It's superfluous. This will work:

int i = 0;
while(fscanf(infile, "%d", *(a + i) != EOF)
{
     i++;
}

Or better yet, to make it more robust:

int i = 0, ret;
while((ret = fscanf(infile, "%d", *(a + i++)) != EOF) && (ret == 1))
    continue;

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 60007

Why not

for (int i = 0; fscanf(infile, "%d", &a[i]) == 1; ++i);

Upvotes: 2

Related Questions