在matlab和c / cpp之间进行fwrite和fread

问题描述

| 当我使用fwrite在MATLAB中保存460个元素的单个变量时出现问题,当我尝试在MATLAB中读取其罚款但尝试在Visual C中使用fread访问相同的bin文件时,对于前88个值给出了很好的结果,但是那么它会遇到EOF或类似的情况,例如,它没有为其余元素提供所需的结果。用于Visual C的代码如下所示。 尽管过去在其他论坛上也曾问过这个问题,但答案并不能解决问题。
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,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);
} 
    

解决方法

        Windows,对吗?默认情况下,文件以文本模式打开,并且字节26被解释为EOF标记。将ѭ1重写为
fopen(\"r01.bin\",\"rb\")
强制以二进制模式打开文件。     ,        您确定MATLAB输出的是float而不是double吗?此代码是不必要的:
// 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 );