简体   繁体   中英

fwrite and fread between matlab and c/cpp

I am having problem when i save a single variable of 460 elements in MATLAB using fwrite and when i try to read in MATLAB its fine but trying to access same bin file using fread in Visual C gives fine result for the first 88 values or so but then it experience EOF or so such as it doesn't give the required result for rest of elements. The code used for Visual C is given as under.

Though this question has been asked in the past post at some other forum as well but the answer doesnot solve the issue.

void main() 
{
FILE *p;
long lsize;
float *temp;
int i;
size_t nn;
// Name of file
printf("Open File: r0.bin ");
p = fopen("r01.bin", "r");
// Determine the size of file
fseek (p, 0 , SEEK_END);
lsize = ftell (p);
rewind (p);
// Allocate memory
int a=sizeof(float);
lsize /= a;
temp = (float*) malloc (a*lsize);
   // Reading the file
nn= fread(temp,a,lsize,p);
// printing the results
for (i=0;i<lsize;i+=4)
  printf("\n %g %g %g %g",temp[i],temp[i+1],temp[i+2],temp[i+3] );
getch();
fclose(p);
} 

Are you sure that MATLAB is outputting floats and not doubles? and this code is a bit unnecessary:

// get rid of these 2 statements
// int a=sizeof(float);
// lsize /= a;

temp = (float*) malloc( lsize );

// Reading the file
nn = fread( temp, 1, lsize, p );

Windows, right? Files are by default open in text mode, and byte 26 is interpreted as EOF marker. Rewrite your fopen as fopen("r01.bin", "rb") to force opening the file in binary mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM