Reputation: 1
I'm having some trouble with using fscanf in C. I've written a random matrix to a file and am now trying to read the data in the text file into another matrix. It seems to read the number of rows and columns fine, but it returns zeros for the data values. I'm completely stuck, so any help would be appreciated!
My MATRIX stucture is declared as
typedef struct matrep {
unsigned rows, columns;
double *data;
}MATRIX;
My file looks like this:
rows = 5, columns = 10
-99.75 12.72 -61.34 61.75 17.00 -4.03 -29.94 79.19 64.57 49.32
-65.18 71.79 42.10 2.71 -39.20 -97.00 -81.72 -27.11 -70.54 -66.82
97.71 -10.86 -76.18 -99.07 -98.22 -24.42 6.33 14.24 20.35 21.43
-66.75 32.61 -9.84 -29.58 -88.59 21.54 56.66 60.52 3.98 -39.61
75.19 45.34 91.18 85.14 7.87 -71.53 -7.58 -52.93 72.45 -58.08
And this is my matrix_read
function:
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, "\n\nrows = %u, columns = %u\n\n", &m, &n) != 2)
{
printf( "Failed to read dimensions\n");
B.data = 0;
B.columns = 0;
B.rows = 0;
}
B.data = (double *)malloc(B.columns*B.rows*sizeof(double));
if(B.data ==0)
{
printf("Failed to allocate memory");
}
fscanf(filep,"\n\nrows = %u, columns = %u\n\n",&m,&n);
rewind(filep);
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;
B.columns = 0;
B.rows = 0;
}
printf("%5.2lf\t", x);
*ptr++ = x;
}
}
B.rows=m;
B.columns=n;
return B;
fclose(filep);
free(ptr);
}
Thanks!
Upvotes: 0
Views: 711
Reputation: 19375
As Alter Mann denoted, drop the second
fscanf(filep,"\n\nrows = %u, columns = %u\n\n",&m,&n);
as well as the
rewind(filep);
moreover, " %5.2lf"
is not a valid scanf conversion specification (you could read the manual about this) - use "%lf"
instead.
Upvotes: 0
Reputation: 41017
You have several problems, one of them is pointed by @simonc, another possible one: you rewind after reading columns and rows in filep
rewind()
sets the position indicator associated with stream to the beginning of the file, you are reading again rows = 5, columns = 10
Finally:
B.data = (double *)malloc(B.columns*B.rows*sizeof(double)); /* Don't cast malloc */
if(B.data ==0)
{
printf("Failed to allocate memory");
/* You have to return or exit here */
}
Upvotes: 1