我们从大学获得了编程任务。我们应该编写一个从bin文件中读取double值的程序。 bin文件中的双精度值具有以下外观:
程序成功将所有值读取为CharArray,但是我不明白如何将带有值的Char数组转换为两倍。我对C语言的编程时间还不够长。我希望有人能帮助我找到解决方案。
到目前为止,我的代码:
typedef struct {
char magic[16];
char dataType[16];
char elementCount[16];
} FileHeader;
typedef struct {
unsigned int n;
double *values;
} FileData;
//---METHODEN
FileData readBinaryValues (const char *filename){
FileData error;
error.n = 0;
error.values = NULL;
FILE *datei = fopen(filename, "rb");
if (datei == NULL){
fprintf(stderr,"ERROR: Datei nicht gefunden\n");
return error;
}
FileHeader fH;
fscanf(datei,"%16c%16c%16c",fH.magic,fH.dataType,fH.elementCount );
char testMagic[16] = "STATDATA";
char testDataType[16] = "DOUBLE";
if ( strcmp(testMagic,fH.magic) != 0){
fprintf(stderr,"ERROR: Unerwarteter Magic\n");
printf("%s\n",fH.magic);
fclose(datei);
printf("%s\n",fH.magic);
return error;
} else if (strcmp(testDataType,fH.dataType) != 0){
fprintf(stderr,"ERROR: Unerwarteter DataType\n");
fclose(datei);
return error;
} else {
int elmentCount = atoi(fH.elementCount);
FileData result;
result.values = (double*) malloc(elmentCount * sizeof(double));
if (result.values == NULL){
fprintf(stderr,"ERROR: Zu wenig HeapSpeicher\n");
fclose(datei);
return error;
}
int posE = (3*16)-1;
fseek(datei, posE , SEEK_SET); //start double-elements
char memBlock [sizeof(double)]; //memoryblock
int j = 0;
int i = 0;
for (j=0;j<=10;j++){ //only 10 doubles for testing
for (i = 0;i<(int)sizeof(double);i++){ //sizeof(double) durchläufe
memBlock[i] = fgetc(datei);
}
if(memBlock == NULL){ //fängt nichts ab
fprintf(stderr,"ERROR: Unerwartetes Dateiende\n");
fclose(datei);
return error;
}
printf("%x\n",memBlock);
snprintf(memBlock,sizeof(double),"%.8e", result.values[j]);
//result.values[j] =strtod(memBlock,NULL);
//result.values (double*)memBlock;
//memcpy(&result.values[j],memBlock,sizeof(double));
//result.values[j] = atof(memBlock);
result.values[j] = *((double*)memBlock);
//result.values[j] = atof(memBlock); //-------------------- string in double
//memcpy(&result.values[j],memBlock,sizeof(double)); //bin -> double
printf("%i)%lf\n",j,result.values[j]);
}
result.n = elmentCount;
return result;
}
}
很抱歉,但是一些注释和错误是用德语编写的。FileHeader描述.bin文件的外观。 Magic首先是dataType,然后是.bin中double元素的数量。紧随其后的是多个double值。程序仍然检查magic = STATDATA和dataType = DOUBLE。