微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在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 );
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。