Lukas Frey - 1 year ago 75
C Question

Read rows and cols from matrix out of a file

I have a Python script which generates a Matrix with double values and saves them in a txt file like this:

-5.70683 -9.72438 5.62137 -3.52453

-3.70381 7.25433 -4.21905 3.88678

-1.43741 7.39768 -6.84103 -3.45817

-5.66966 3.47989 -5.64204 -6.08512

Now I have to read the .txt file in a C file and convert it to my struct:

``````struct Matrix {
int rows;
int columns;
double **matrix;
};
``````

This is my C file:

``````Matrix *readMatrix(const char filename[]) {
Matrix matrix;
FILE * matrix_file;
char * str;
int i, j;

//allocate pointer
matrix.matrix = malloc(4 * sizeof(double *));
for(i = 0; i < 4; i++)
matrix.matrix[i] = malloc(4 * sizeof(double *));

matrix_file = fopen(filename, "r");

for(i = 0; i < 4; i++) {
for(j = 0; j < 4; j++) {
if (!fscanf(matrix_file, "%lf", &matrix.matrix[i][j]))
break;

printf("%lf\n",matrix.matrix[i][j]);
}
}
fclose(matrix_file);
return &matrix;
}
``````

Instead of allocate it to a 4x4 matrix I want to allocate my Pointer dynamic. So I have to read out of my file the rows and cols. How can I do this?