[英]fwrite and fread between matlab and c/cpp
当我使用 fwrite 在 MATLAB 中保存 460 个元素的单个变量时遇到问题,当我尝试在 MATLAB 中读取时,它很好,但尝试使用 fread 在 Visual Z0D61F8370CAD1D412F80B84D143 中访问相同的 bin 文件,所以给出了第一个很好的结果然后它会遇到 EOF 左右,例如它没有为元素的 rest 提供所需的结果。 用于 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);
}
您确定 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 );
Windows,对吧? 文件默认以文本模式打开,字节 26 被解释为 EOF 标记。 将fopen
重写为fopen("r01.bin", "rb")
以强制以二进制模式打开文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.