2
我在C中編寫了一些代碼來讀取包含複數的二進制文件。它有效,但我對我需要演出的演員感到不舒服。有沒有更好的辦法?速度在我的程序中非常重要(我通過將代碼從C++ iostreams更改爲C stdio函數來將執行時間加倍)。它可以做得更快嗎?有沒有更好的方法來讀取C中的複雜二進制數據?
這裏是我的代碼:
#include<complex.h>
#include<errno.h>
#define spaceh 6912
#define Nc 3
#define dirac 4
... ...
typedef double complex dcomplex;
long size;
size_t result;
char filename[84];
char* buffer;
dcomplex* zbuff;
int i, j, k, srccol, srcdir;
srcdir = 1;
srccol = 2;
/* allocate array dcomplex QM[dirac][Nc][space] on the heap */
sprintf(filename, "/<path>/file.%d.%d.bin", srcdir, srccol);
FILE* input;
input = fopen(filename, "rb");
if(readfile)
{
fseek(input, 0, SEEK_END);
size = ftell(input);
rewind(input);
buffer = (char*)malloc(sizeof(char)*size);
if(buffer == NULL)
{
fputs("Buffer allocation failed.", stderr);
exit(1);
}
result = fread(buffer, 1, size, input);
if(result != size)
{
fputs("File reading failed.", stderr);
exit(2);
}
/* The cast I'm referring to */
zbuff = (dcomplex*)buffer;
}
else
{
printf("File was not successfully opened: %s\n", strerror(errno));
}
count = 0;
for(k = 0; k < space; k++)
{
for(j = 0; j < Nc; j++)
{
for(i = 0; i < dirac; i++)
{
QM[i][j][k] = convert_complex(zbuff(count));
count++;
}
}
}
free(buffer);
fclose(input);
的convert_complex功能反轉單複數的字節順序。我對此更不舒服,但我不希望我的問題變得太大。
你爲什麼沒有聲明緩衝區爲'dcomplex * buffer'的原因? – Neo 2011-02-06 22:45:32
沒有理由,除了可能是因爲我最初收到C++版本的建議,C++版本使用從char *到reindex *的reinterpret_cast到dcomplex *。也許在C版本中,我應該直接完成它。 – 2011-02-06 22:55:50