Hey guys
I'm writing a programme to generate a random matrix, print it to a file and then read from the file and print to the screen. I'm having some issues with reading from the file. My programme reads in the number of rows and columns in my matrix fine but I can't seem to get it to read in the data values properly. I'm completely stuck so any help at all would be very appreciated!
Here's the structure of my matrix:
Code:
typedef struct matrep {
unsigned rows, columns;
double *data;
}MATRIX;
Here's my write_matrix function (prints to a txt file)
Code:
void matrix_write(FILE *filep, MATRIX A)
{
int i, j;
double *ptr;
ptr=A.data;
if((filep = fopen("matrixA.txt","w"))==NULL)
{
printf("\nFailed to Open File.\n");
exit(1);
}
fprintf(filep, "rows = %d, columns = %d\n", A.rows, A.columns);
for(i=0; i<A.rows; i++)
{
fprintf(filep, "\n");
for(j=0; j<A.columns; j++)
{
fprintf(filep, " %5.2lf", *ptr++);
}
}
fclose(filep);
free(ptr);
}
and here's my read_matrix file (attempts to read the matrix from the txt file)
Code:
MATRIX matrix_read(char file_name[15])
{
int i,j, m, n;
MATRIX B;
FILE *filep;
double *ptr = NULL;
double x;
if((filep = fopen("matrixA.txt", "r"))==NULL)
{
printf("\nFailed to open File.\n");
}
if(fscanf(filep, "rows = %u, columns = %u\n", &m, &n) != 2)
{
printf( "Failed to read dimensions\n");
n = 0;
m = 0;
}
B.data = malloc(sizeof(double)*m *n);
if(B.data ==0)
{
printf("Failed to allocate memory");
exit(1);
}
fscanf(filep,"rows = %u, columns = %u\n",&m,&n);
ptr = B.data;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
if (fscanf(filep, " %5.2lf", &x) != 1)
{
printf("Failed to read element [ %d,%d ]\n", i, j);
B.data=0;
}
printf("%5.2lf\t", x);
*ptr++ = x;
}
}
B.rows=m;
B.columns=n;
return B;
fclose(filep);
free(ptr);
}
Thanks!