Lukas Frey - 5 months ago 27

C Question

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?

Answer

Assuming you do not know *a priori* the number of rows and cols and want to deduce it from the file, a simple way would be to:

- read first line, parse it and deduce the number of cols, say M
- allocate an array of N=M arrays of M doubles -> if allocation error, then fatal error
- store values from the first line in the first row of the array
- loop:
- read a new line and parse it -> if empty line or end of file return the matrix (
**not**its address!) - ensure that it contains M elements -> if not fatal error
- if there is no more place in the array realloc with new size being N = 2 * N
- if allocation error, then fatal error

- store values from the line in next row

- read a new line and parse it -> if empty line or end of file return the matrix (