我正在尝试从二进制文件中读取结构到结构数组但是我一直在分段错误,任何人都可以帮我解释我的代码有什么问题吗?我相信错误是我如何将字符串放入结构数组中,但我不确定。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 150
struct theContacts {
unsigned long phone;
long namePos;
long lastNamePos;
long emailPos;
long next;
};
typedef struct theContacts record;
struct livememory {
char first[MAX];
char last[MAX];
char email[MAX];
unsigned long phone;
};
typedef struct livememory livemem;
int main (void) {
record *recPtr1;
livemem strings[1000];
FILE *fptr;
long file_end;
int i;
fptr = fopen("contacts.db", "a+");
if (fptr == NULL) {
printf("Error opening file\n");
printf("please try again\n");
exit(0);
}
fseek(fptr, 0, SEEK_END);
file_end = ftell(fptr);
while(1) {
recPtr1 = malloc (sizeof(record));
fread(recPtr1, sizeof(record), 1, fptr);
fseek(fptr, recPtr1->namePos, SEEK_SET);
fgets(strings[i].first, MAX, fptr);
fseek(fptr, recPtr1->lastNamePos, SEEK_SET);
fgets(strings[i].last, MAX, fptr);
fseek(fptr, recPtr1->emailPos, SEEK_SET);
fgets(strings[i].email, MAX, fptr);
i++;
fseek(fptr, recPtr1->next, SEEK_SET);
if (recPtr1->next == file_end) {
break;
}
}