将结构数组写入C中的二进制文件

Joh*_*uay 5 c arrays binary struct file

我有一个结构数组,我想写入二进制文件.我有一个write.c程序和一个read.c程序.write.c程序似乎工作正常,但是当我运行read.c程序时,我遇到了分段错误.我是C的新手所以如果有人可以查看我的代码以查找任何明显的错误,那将会很棒.我保证不会太久:)

为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;
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助!

asc*_*ler 5

struct Person* people;
Run Code Online (Sandbox Code Playgroud)

这只分配一个指向struct的指针,但是你没有为实际的struct内容分配任何空间.要么malloc类似于你的写程序,或尝试类似的东西:

struct Person people;
fread(&people, sizeof(people), 1, data);
Run Code Online (Sandbox Code Playgroud)