簡體   English   中英

matlab 和 c/cpp 之間的 fwrite 和 fread

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM