matlab与c/cpp之间的fwrite和fread

fwrite and fread between matlab and c/cpp

本文关键字:fwrite fread 之间 cpp matlab      更新时间:2023-10-16

当我使用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, 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);
} 

Windows,对吗?默认情况下,文件以文本模式打开,字节26被解释为EOF标记。将fopen重写为fopen("r01.bin", "rb"),以强制以二进制模式打开文件。

您确定MATLAB输出的是浮点值而不是双精度值吗?这个代码有点多余:

// 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 );