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

时间:2010-12-06 16:34:20

标签: c arrays file binary struct

我有一个结构数组,我想写入二进制文件。我有一个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;
}

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

感谢您的帮助!

4 个答案:

答案 0 :(得分:5)

struct Person* people;

这只分配一个指向struct的指针,但是你没有为实际的struct内容分配任何空间。要么像编写程序一样使用malloc,要么尝试类似:

struct Person people;
fread(&people, sizeof(people), 1, data);

答案 1 :(得分:3)

您需要先为此人分配内存。将struct Person* people;更改为struct Person* people = malloc(sizeof(struct Person));。不要忘记最后释放你的记忆:free(people);

答案 2 :(得分:1)

在执行malloc之前,您需要people内存到指针变量fread,或者(更简单)直接读入本地变量:

struct Person people;

fread(&people, sizeof(struct Person) * 1/* Just read one person */, 1, data);

答案 3 :(得分:1)

您需要为正在阅读的数据分配空间:

people = malloc(sizeof(*people)*numPeople);