I'm trying to use fscanf to read a file containing 25 ints and store them in memory. However, it appears that for the first 12 values, instead of scanning the actual int in the file fscanf is always showing up as 1. The 13th value shows up as -1, and then the while loop in the code below terminates. Any idea why this might be? Thanks for your help.
#include <stdio.h>
#include <stdlib.h>
#include "matrix.h"
#define ROWS 5
#define COLS 5
void load_file(FILE* file, int** p);
int main()
{
FILE* f1;
f1 = fopen("twenty-five-ints.txt", "r");
int p=0;
int* matrix = &p;
load_file(f1, &matrix);
}
void load_file(FILE* file, int** p) {
*p = malloc(25*sizeof(int));
int number = 0;
int i = 0;
while (fscanf(file, "%d", &number) != EOF) {
*(*p + i) = fscanf(file, "%d", &number);
printf("%d ", *(*p + i));
i++;
}
printf("\n");
}
The printf statement inside the while loop prints out 12 ones separated by spaces, followed by a -1.
while (fscanf(file, "%d", &number) == 1)is the proper condition, then do not call it again inside the loop. Also, no need to initializeint* matrix = &p;if you are simply passingmatrixtoload_filefor allocation. - David C. Rankin