Hi there,
Please, could anyone tell me why I am not getting the expected result when running this code?
Code:
#import <Foundation/Foundation.h>
typedef int64_t msize_t[2];
int getMatrixSizeFromFile(const char *filePath, msize_t *matrixSize);
int getMatrixSizeFromFile(const char *filePath, msize_t *matrixSize)
{
FILE *fid;
fid=fopen(filePath,"r");
if (fid!=NULL)
{
float_t ffloat;
int64_t fchar;
int64_t counter[2]={-2,1};
fpos_t position[3];
position[1]=-1;
fgetpos(fid,&position[2]);
while (position[1]!=position[2])
{
counter[0]++;
position[0]=position[1];
position[1]=position[2];
fscanf(fid,"%f",&ffloat);
fgetpos(fid,&position[2]);
}
rewind(fid);
for (int64_t i=0; i<position[0]; i++) {
fchar=fgetc(fid);
if (fchar=='\n') counter[1]++;
}
fclose(fid);
if (counter[0]%counter[1]==0) {
*matrixSize[0]=counter[1];
*matrixSize[1]=counter[0]/counter[1];
printf("From Function => Matrix size: %lli x %lli.\n",*matrixSize[0],*matrixSize[1]);
} else {
printf("Error: File does not contain a matrix.\n");
return -2;
}
} else {
printf("Error: File could not be opened.\n");
return -1;
}
return 0;
}
int main (int argc, const char * argv[])
{
const char *filePath="/mymatrix.txt";
FILE *pFile=fopen(filePath,"w+");
for (int i=0; i<7; i++)
{
if (i>0) fputs("\n",pFile);
for (int j=0; j<4; j++)
fprintf(pFile,"%.5f ",3/8.*(float)i-5*(float)j);
}
fclose(pFile);
msize_t msize={0,0};
getMatrixSizeFromFile(filePath,&msize);
printf("From Main => Matrix size: %lli x %lli.\n",msize[0],msize[1]);
return 0;
}
In theory, the result should be:
From Main => Matrix size: 7 x 4.
when function main is evaluated, but instead I am getting:
From Main => Matrix size: 7 x 0.
Any idea?
Thank you very much. Any help will be greatly appreciated.