[英]Problem while reading structure from binary file
As I was trying to write code which is supposed to sort some structures in a file by a specific field (key), I noticed that my function won't read the key correctly. 当我尝试编写应按特定字段(键)对文件中某些结构进行排序的代码时,我注意到我的函数无法正确读取键。 I don't have any idea what I am doing wrong.
我不知道我在做什么错。 The code is not complete.
代码不完整。
The constr
function is supposed to read one structure at a time from the binary file, then only save the varsta
array. 应该使用
constr
函数一次从二进制文件读取一个结构,然后仅保存varsta
数组。 However, if I try to see what value I obtained, the values are not the ones I gave. 但是,如果我尝试查看获得的值,则这些值不是我提供的值。
This is my code: 这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char nume[20];
char prenume[20];
float varsta;
} PERS;
typedef struct
{
float key;
int nr;
}INDEX;
int constr(FILE *f, INDEX tabl[])
{
int n;
n = ftell(f) / sizeof(PERS);
int i, depl = 0;
PERS p;
for (i = 0; i < n; i++)
{
fseek(f, depl, 0);
fread(&p, sizeof(p), 1, f);
tabl[i].key = p.varsta;
tabl[i].nr = i;
depl += sizeof(PERS);
}
return n;
}
int main()
{
FILE *f;
PERS pers[3];
if ((f = fopen("fis.txt", "wb+")) == NULL)
{
printf("Not ok");
exit(1);
}
int i;
for (i = 0; i < 3; i++)
{
scanf("%s%s%f", &pers[i].nume, &pers[i].prenume, &pers[i].varsta);
fwrite(&pers[i], sizeof(PERS), 1, f);
}
INDEX tabl[3];
int n = constr(f, tabl);
printf("%d", tabl[2].key); //only to check if the key is correct
fclose(f);
}
The key
field is a float, but you are trying to print an integer. key
段是一个浮点数,但是您正在尝试打印一个整数。
Change the penultimate line in your code to 将代码中倒数第二行更改为
printf("%.2f\n", tabl[2].key);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.