Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing an array of structs to a binary file in C

I have an array of structs I would like to write to a binary file. I have a write.c program and a read.c program. The write.c program seems to be working properly but when I run the read.c program I get a segmentation fault. I'm new to C so It would be great if someone could look over my code for any obvious errors. I promise it's not too long :)

write.c:

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

struct Person 
{
    char f_name[256];
    char l_name[256];
    int age;
};

int main(int argc, char* argv[])
{
    struct Person* people;
    int people_count;

    printf("How many people would you like to create: ");
    scanf("%i", &people_count);
    people = malloc(sizeof(struct Person) * people_count);  

    int n;
    for (n = 0; n < people_count; n++)
    {
        printf("Person %i's First Name: ", n);
        scanf("%s", people[n].f_name);

        printf("Person %i's Last Name: ", n);
        scanf("%s", people[n].l_name);

        printf("Person %i's Age: ", n);
        scanf("%i", &people[n].age);
    }

    FILE* data;
    if ( (data = fopen("data.bin", "wb")) == NULL )
    {
        printf("Error opening file\n");
        return 1;   
    }

    fwrite(people, sizeof(struct Person) * people_count, 1, data);
    fclose(data);

    return 0;
}

read.c:

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

struct Person 
{
    char f_name[256];
    char l_name[256];
    int age;
};

int main(int argc, char* argv[])
{
    FILE* data;
    if ((data = fopen("data.bin", "rb")) == NULL)
    {
        printf("Error opening file\n");
        return 1;
    }

    struct Person* people;

    fread(people, sizeof(struct Person) * 1/* Just read one person */, 1, data);
    printf("%s\n", people[0].f_name);

    fclose(data);

    return 0;
}

Thanks for the help!

like image 773
John Jacquay Avatar asked Dec 06 '10 16:12

John Jacquay


1 Answers

struct Person* people;

This allocates just a pointer to struct, but you don't have any allocated space for actual struct contents. Either use malloc similarly to your write program, or try something like:

struct Person people;
fread(&people, sizeof(people), 1, data);
like image 80
aschepler Avatar answered Nov 04 '22 00:11

aschepler