How to read an array of bin file structure in C

I have this code that works for me:

 fp = fopen("person.dat", "rb");
    struct Person{
        int pnummer;
        char name[20];
        float lenght;
        float weight;
    };
    struct Person*object=malloc(sizeof(struct Person));
    fread(object, sizeof(struct Person), 1, fp);
    printf("%s\n%d\n%f\n%f\n",object->name,object->pnummer,object->lenght,object->weight);

      

Withdrawal: Andreas 660311 181.000000 82.000000

I would like to read an array of this structure. So I can have 10 people. How do I write the last 3 lines?

typedef struct{
    int pnummer;
    char name[20];
    float lenght;
    float weight;
}Person;
Person p_lista[10];

      

+3


source to share


2 answers


Here is the complete code to read and write



#include <stdio.h>
#include <stdlib.h>

struct Person {
    int pnummer;
    char name[20];
    float lenght;
    float weight;
};

int main(void) {
    FILE* fp;
    int i;
    int count = 10;
    /* let say we have array of 10 persons  */
    struct Person src[10] = {
            { 1, "John",    1, 1},
            { 2, "Mary",    2, 2},
            { 3, "Charles", 4, 3},
            { 4, "Arnold",  5, 4},
            { 5, "Ted",     3, 5},
            { 6, "Rachel",  5, 6},
            { 7, "David",   6, 7},
            { 8, "Jim",     7, 8},
            { 9, "Alan",    8, 9},
            {10, "Lisa",    9, 0},
    };

    /* write 10 persons to file */
    fp = fopen("person.dat", "wb");
    fwrite(src, sizeof(struct Person), count, fp);
    fclose(fp);

    /* read 10 persons to file */
    fp = fopen("person.dat", "rb");
    struct Person* objects = malloc(count * sizeof(struct Person));
    fread(objects, sizeof(struct Person), count, fp);
    fclose(fp);

    /* output result */
    for(i = 0; i < 10; ++i) {
        printf("%s\n%d\n%f\n%f\n", objects[i].name, objects[i].pnummer, objects[i].lenght, objects[i].weight);
    }


    /* Without dynamic memory allocation */
    struct Person p_lista[10];
    /* number of persons to read */
    int size = sizeof(p_lista) / sizeof(struct Person);
    fp = fopen("person.dat", "rb");
    fread(p_lista, sizeof(struct Person), size, fp);
    fclose(fp);

    /* output result */
    for(i = 0; i < 10; ++i) {
        printf("%s\n%d\n%f\n%f\n", p_lista[i].name, p_lista[i].pnummer, p_lista[i].lenght, p_lista[i].weight);
    }

    return 0;
}

      

+2


source


Person p_lista[10];
...
fread(p_lista, sizeof(struct Person), 10, fp);

      



For simplicity, there are no errors.

+4


source







All Articles