user3921351
user3921351

Reputation: 23

Read file line by line storing ints in array

Im trying to read a file containing

000101001001010000000000000 (each number is on a new line)

This is the code im using

FILE *fatfile;

int i;
i = 0;

fatfile = fopen("fat.dat", "r");
if(fatfile == NULL)
{
    perror("Error while opening file");
}

int number;

while((fscanf(fatfile, "%d", &number) == 1) && (i < 32))
{
    fscanf(fatfile, "%d", &number);
    fat[i] = number;
    i++;
}

fclose(fatfile);

however the output im getting is all 0s

How do i do this correctly

Upvotes: 0

Views: 81

Answers (1)

erickg
erickg

Reputation: 985

while((fscanf(fatfile, "%d", &number) == 1) && (i < 32))
{
    // you already read the number from the file above,
    // you need to save it after read the new value.
    // and fscanf is executed every time since it's in the while's condition.
    fat[i++] = number;

}

It works like this:

  1. check (fscanf(fatfile, "%d", &number) == 1) && (i < 32).
  2. If it is true, then it execute its body.

If you read the value again in the loop, you would miss something.

Upvotes: 1

Related Questions