使用MatLab编写的二进制文件在C中部分正确读取,但大多数都是错误的

时间:2018-02-23 12:43:58

标签: c matlab binaryfiles

我已在MatLab(R2017b)中编写了一些代码,我现在试图通过在C中编写脚本等效来获得相同的结果。出于代码的目的,重要的是一些数量等于数值精度(使用双精度)。 要处理的数量是[900x522]矩阵matrix_in。使用MatLab,我已经写了这个矩阵的内容 - 由维数和每个维度的范围所取代 - 作为二进制文件data.bin的两倍(每个值8个字节),即:

dim = size(matrix_in);
N = length(size(dim));

fileID = fopen(file_out,'w');
fwrite(fileID,N,'double');    % number of dimensions, usually 2
fwrite(fileID,dim,'double');  % [nrows, ncols, ..]
fwrite(fileID,matrix_in,'double');
fclose(fileID);

接下来,我想用c-code读取这个二进制文件的内容。为此,我在visual studio 15中编写了以下代码:

#include <cstdio>
#include <cstdlib>

int main(int argc, char *argv[])
{

const char *fname = argv[1];
FILE * myPtr;
myPtr = fopen(fname, "r");
// Test if input file exists, abort if it does not:
if (!myPtr) {
    printf("\nUnable to open file: > %s <, are you sure it exists? Aborting program.\n", fname);
    return -1;
}

/* Read in values from binary file here
 Format:
 - First byte:               N   = number of dimensions of matrix (bytes 1:8)
 - N*8 next bytes:           dim = extent of matrix in all N dimensions (bytes 9:(n+1)*8)
 - prod(dim)*8 next bytes:   A   = values of matrix (column-wise) (8 bytes per value)
*/

// Read N:
double n;
fread(&n, sizeof(double), 1, myPtr);
int N = (int)n;
printf("The value of N = %d\n", N);   // This prints 2, as it should

// Read dim:
double *dim = (double *)malloc(N * sizeof(double));
fread(dim, sizeof(double), N, myPtr);
printf("The values of dim are %f,%f.\n", dim[0],dim[1]); // This prints 900.000000,522.000000, as it should

// Read A:
int Nel = (int)(dim[0] * dim[1]);                   // Number of elements in A;
double *A = (double *)malloc(Nel * sizeof(double)); // Allocate memory to store A;
fread(A, sizeof(double), 150, myPtr);               // Read in values to A;
printf("There are %d elements in array A.\n", Nel); // This prints 469800, as it should

// This is where the incorrectness shows:
for (int i = 0; i < 136; i++) {
    printf("%d: %.8f: %p \n", i, A[i],*A+i);
}

// Close file, deallocate memory, and exit
fclose(myPtr);
free(dim);
free(A);
printf("End of program reached.\n");
return 0;

}

那么出了什么问题?好吧,当我构建项目(使用Visual Studio 15),并使用.bin文件运行可执行文件时,输出如下:

The value of N = 2
The values of dim are 900.000000,522.000000.
There are 469800 elements in array A.
0: -0.19632467: BFC9212AADC25959
1: -0.05302308: 3FE9B7B5548F69AA
2: 0.12151127: 3FFCDBDAAA47B4D5
3: -0.11154920: 40066DED5523DA6A
// and so forth, until..
132: 0.11697594: 406079B7B5548F6A
133:-6277436239688796889934943738416506716724917685420501794480371793920.00: 406099B7B5548F6A
134:-6277438562204192487878988888393020692503707483087375482269988814848.00: 4060B9B7B5548F6A
135:-6277438562204192487878988888393020692503707483087375482269988814848.00: 4060D9B7B5548F6A

这一直持续到最后一个值,即A [Nel-1]。读入的前133个值与MatLab中的完全相同,达到双倍精度,正如您所期望的那样。出于某种原因,事后出了问题。现在,.bin文件的内容大小正确,当我将其读入matlab而不是C时,结果很好。有没有人知道我的C代码出了什么问题?

0 个答案:

没有答案