我用 C 编写了一些代码来读取包含复数的二进制文件。它有效,但我对我需要执行的演员阵容感到不舒服。有没有更好的办法?速度在我的程序中至关重要(我通过将代码从 C++ iostreams 更改为 C stdio 函数,使执行时间加倍)。也可以做得更快吗?
这是我的代码:
#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 函数反转单个复数的字节顺序。我对此更不舒服,但我不希望我的问题变得太大。