lighter
lighter

Reputation: 2806

fscanf read file using c

My data.txt content is:

1 2 3 4 5 6
1 2 3 4 5 6
4 5 6 7 8 2

I read the file, and store the value to a two dimension int array

  int record[line_number][6]; 
  int record2[line_number][8];
  int test;

  for(i = 0; i <line_number; i++)
  {
    for(j = 0; j <6; j++)
    {
      fscanf(fptr, "%d", &record[i][j]);
    }
  }
  int a=0;
  int b=0;
  for(a=0; a<i; a++) {
    for(b=0; b<6; b++) {
      printf("%d,", record[a][b]);
    }
    printf("\n");
  }

The output like a memory address, what wrong in my code? Thanks!

Upvotes: 0

Views: 156

Answers (1)

unwind
unwind

Reputation: 400049

You don't check the return value of fscanf(), so you don't know that it really succeeds for all the conversions. If it fails, the value in record[][] will be uninitialized, and printing it out will print whatever happens to be in memory.

Upvotes: 6

Related Questions