gpt4 book ai didi

c - 读取二进制文件并将所有数据存储到结构数组中

转载 作者:太空宇宙 更新时间:2023-11-04 04:56:47 25 4
gpt4 key购买 nike

我需要编写一个简单的测量转换程序。程序首先询问用户二进制文件的名称(单位转换数据),打开文件,并设置数组。

我的结构:

struct unit {               
char name[NAME_LEN];
char abbrev[ABBREV_LEN];
char class[CLASS_LEN];
double standard;
};

和我的功能:

int fread_units(int unit_max,struct unit units[], int *unit_sizep)
{
FILE *filep;
struct unit data;
int i, status;
char fullname[10];

/* Gets database of units from file */

printf("Enter name of binary file> ");
scanf("%s", fullname);
strcat(fullname, ".bin");
i = 0;
filep = fopen(fullname, "rb");
//fseek (filep , 0 , SEEK_END);
for (status = fread(&data, sizeof( struct unit ), 1, filep);
status == 1 && i < unit_max;
status = fread(&data, sizeof( struct unit ), 1, filep)){
units[i++] = data;
}
printf("\n%f", units[3].standard);
/* Issue error message on premature exit */
if (status == 0) {
printf("\n*** Error in data format ***\n");
printf("*** Using first %d datavalues ***\n",i);
}
else if (status != EOF) {
printf("\n*** Error: too much data in file ***\n");
printf("*** Using first %d data values ***\n", i);
}

/* Send back size of used portion of array */
*unit_sizep = i;

if(status == 4)
status = 1;
else if (status != EOF)
status = 0;
fclose(filep);

return(status);
}

根据书上的说法,(fread(&data, sizeof(struct unit), 1, filep);)足以将所有数据存储到一个结构中。

但它对我不起作用......

输出:

*** Error in data format ***
*** Using first 4 datavalues ***
To convert 25 kilometers to miles, you would enter
> 25 kilometers miles
or, alternatively,
> 25 km mi
> 25 km mi
Attempting conversion of 25.0000 km to mi . . .
Unit kmnot in database

Enter a conversion problem or q to quit.
>

我的 units.bin 文件;

miles                   mi          distance        1609.3
kilometers km distance 1000
yards yd distance 0.9144
meters m distance 1
quarts qt liguid_volume 0.94635
liters l liquid_volume 1
gallons gal liquid_volume .7854
millimeters ml liquid_volume 0.001
kilograms kg mass 1
grams g mass 0.001
slugs slugs mass 0.14594

最佳答案

我解决了我的问题。我用以下代码创建了一个二进制文件。

#include <stdio.h>

#define NAME_LEN 30
#define ABBREV_LEN 15
#define CLASS_LEN 20
#define MAX_UNITS 20

struct unit {
char name[NAME_LEN];
char abbrev[ABBREV_LEN];
char class[CLASS_LEN];
double standard;
};

int main(void)
{
int i;
struct unit unitp[MAX_UNITS];
FILE *inp, *outp;
inp = fopen("units.dat", "r");
outp = fopen("units.bin", "wb");
for(i=0;!feof(inp);i++){
fscanf(inp, "%s%s%s%lf", unitp[i].name,
unitp[i].abbrev,
unitp[i].class,
&unitp[i].standard);
}
fwrite(unitp, sizeof(struct unit ), i, outp);

fclose(inp);
fclose(outp);

return(0);
}

和我的 for 循环;

for (status = fread(&units[i++], sizeof( struct unit ), 1, filep);
i < MAX_UNITS && !feof(filep);
status = fread(&units[i++], sizeof( struct unit ), 1, filep)){
//units[i++] = data;
}

关于c - 读取二进制文件并将所有数据存储到结构数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6361883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com