My exercise is to load 2 matrices from 2 files with unknown sizes and multiply them together if it is possible. I should also load each file once. I could do it with loading the file twice as you can see below, but how could I do with loading the file only once?
typedef struct matrix_ {
int r, c;
double* dat;
} matrix;
int rows(char* fn) {
int lines = 1;
int ch;
FILE* fp = fopen(fn, "r");
while(!feof(fp)) {
ch = fgetc(fp);
if(ch == '\n') {
lines++;
}
}
return lines;
}
matrix loadmatrix(char* fn) {
FILE* file = fopen(fn, "r");
int size = 5*5;
matrix mat;
mat.r = rows(fn);
mat.dat = malloc(size*sizeof(double));
double input;
int i = 0;
do {
if (fscanf(file, "%lf", &input)==1) {
if(i == size-1) {
size = 4*size;
mat.dat = realloc(mat.dat, size*sizeof(double));
}
mat.dat[i] = input;
i+=1;
}
} while (!feof(file));
mat.c = ((i+1)/(mat.r));
return mat;
}