Mary Poppins
Mary Poppins

Reputation: 79

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. 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);
}

Upvotes: 0

Views: 60

Answers (1)

David Collins
David Collins

Reputation: 3032

The key field is a float, but you are trying to print an integer.

Change the penultimate line in your code to

printf("%.2f\n", tabl[2].key);

Upvotes: 3

Related Questions