编辑了代码,使其更简单,并且没有链接列表指针。
这是我的结构
typedef struct megye
{
int megye;
int hektar1_min;
int hektar1_max;
int hektar1_tam;
int hektar2_min;
int hektar2_max;
int hektar2_tam;
int hektar3_min;
int hektar3_tam;
}megye;
并且我尝试了不带“ struct _megye * next;”的情况。线也。
这是我的代码:
int main()
{
FILE *fb;
megye*p;
p=(megye*)calloc(8,sizeof(megye));
fb=fopen("tamogatas.dat", "rb");
if (fb==NULL)
{
printf("couldn't open file");
}
while (fread(p, sizeof (megye), 7, fb))
{
printf("%d\n", p->megye);
}
fclose(fb);
_CrtDumpMemoryLeaks();
free(p);
return 0;
}
这是文本文件中的一行,我将其转换为此处使用的二进制文件:
1 50 100 2 100 200 4 200 6
我的目标是将每一个数字放在结构的int的一行中。
程序运行,将随机数放入结构中(始终更改,长数从6位到大约13-14)。调试器说,他的fread函数读取文件的第一行(fread的_base字符串),但根本没有将其放入结构中。我该怎么做才能将我的数字输入结构中?
请简单一点,我两天没睡觉了:(
编辑:我必须用二进制文件来完成它,因为这是家庭作业。
一条记录读/写到二进制文件的示例
int main(){
FILE *fb;
megye orig = {1, 50, 100, 2, 100, 200, 4, 200, 6 };
megye *p;
fb=fopen("megye.dat", "wb");
fwrite(&orig, sizeof(megye), 1, fb);//1 record of struct megye to binary file of megye.dat
fclose(fb);
p=(megye*)calloc(1, sizeof(megye));//memory ensure 1 record of struct megye
fb=fopen("megye.dat", "rb");
if (fb==NULL)
{
printf("couldn't open file");
}
while (1==fread(p, sizeof(megye), 1, fb))//1 :read number of record
{
printf("%d %d ...\n", p->megye, p->hektar1_min);
}
fclose(fb);
//_CrtDumpMemoryLeaks();
free(p);
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句