简体   繁体   English

matlab 和 c/cpp 之间的 fwrite 和 fread

[英]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.当我使用 fwrite 在 MATLAB 中保存 460 个元素的单个变量时遇到问题,当我尝试在 MATLAB 中读取时,它很好,但尝试使用 fread 在 Visual Z0D61F8370CAD1D412F80B84D143 中访问相同的 bin 文件,所以给出了第一个很好的结果然后它会遇到 EOF 左右,例如它没有为元素的 rest 提供所需的结果。 The code used for Visual C is given as under.用于 Visual C 的代码如下所示。

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?您确定 MATLAB 输出的是浮点数而不是双精度数吗? 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? Windows,对吧? Files are by default open in text mode, and byte 26 is interpreted as EOF marker.文件默认以文本模式打开,字节 26 被解释为 EOF 标记。 Rewrite your fopen as fopen("r01.bin", "rb") to force opening the file in binary mode.fopen重写为fopen("r01.bin", "rb")以强制以二进制模式打开文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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