2010-12-06 146 views
5

我有一個我想寫入二進制文件的結構數組。我有一個write.c程序和一個read.c程序。 write.c程序似乎工作正常,但是當我運行read.c程序時,出現了分段錯誤。我是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; 
} 

感謝您的幫助!

+0

這個問題每天會被詢問多少次?應該有一個'C'的常見問題解答,讓我們指出答案,而不是花時間寫下所有這些停頓的時間...... – KevinDTimm 2010-12-06 16:57:51

回答

5
struct Person* people; 

這隻分配一個指向struct的指針,但是你沒有爲實際結構內容分配任何空間。要麼使用malloc類似於你寫程序,或者你可以試試:

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

您可能需要malloc內存爲指針變量people你做fread,或(容易)之前只是直接讀入一個局部變量:

struct Person people; 

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

您需要分配用於數據空間,你正在閱讀:

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

一旦OP決定讀取大於1的元素,這似乎更具可擴展性。可以在一個局部變量上循環。 – 2010-12-06 16:39:14

3

您需要先爲該人分配記憶。將struct Person* people;更改爲struct Person* people = malloc(sizeof(struct Person));。並且不要忘記最後釋放你的記憶:free(people);

+0

你可以解釋什麼時候(struct Person *)意味着在malloc(sizeof(struct Person))之前?這是演員嗎? – 2010-12-06 16:50:43