我是一个C初学者。在经历了许多教程之后,我不确定为什么我会出现分割错误。我在函数write_new_file和search_by_firstname上都出现了此错误。我认为问题出在我的函数write_new_file中记录的参数类型PERSON*中。我已经尝试将它从指针更改为inrecord,并相应地更改了所有变量,但问题仍然存在。我已经问过同学了,但还没有解决办法。
//------TYPEDEFS------
typedef struct{
char firstname[20];
char famname[20];
char pers_number[13]; //yyyymmddnnnc
}PERSON;
void write_new_file(PERSON *inrecord){
FILE *ptr_myfile;
ptr_myfile=fopen("test.bin","w");
if (ptr_myfile==NULL)
{
printf("Unable to open file!");
exit(0);
}
strcpy(inrecord->firstname,"Name",20);
strcpy(inrecord->famname, "surname",20);
strncpy(inrecord->pers_number, "880192234",13);
fwrite(&inrecord, sizeof(PERSON), 1, ptr_myfile);
fclose(ptr_myfile);
}
void search_by_firstname(char *name){
FILE *ptr_myfile;
ptr_myfile=fopen("test.bin","r");
PERSON *temp=NULL;
if (ptr_myfile==NULL)
{
printf("Unable to open file!");
exit(0);
}
fread(temp,sizeof(PERSON),1,ptr_myfile);
if(strcmp(temp->firstname,name)!=0){
printf("Not found");
}else{
printf("found");
}
fclose(ptr_myfile);
}
int main(void){
PERSON *ppost=NULL;
write_new_file(ppost);
search_by_firstname("Neda");
return(0);
}
-
您在中丢弃了一个
NULL
指针void write_new_file(PERSON *inrecord) { FILE *ptr_myfile; ptr_myfile = fopen("test.bin","w"); if (ptr_myfile == NULL) { printf("Unable to open file!"); exit(0); } strcpy(inrecord->firstname, "Name", 20); strcpy(inrecord->famname, "surname", 20); strncpy(inrecord->pers_number, "880192234", 13); fwrite(&inrecord, sizeof(PERSON), 1, ptr_myfile); fclose(ptr_myfile); }
您不需要向写入文件函数传递指针,您需要的是
void write_new_file() { FILE *ptr_myfile; PERSON person; ptr_myfile = fopen("test.bin","w"); if (ptr_myfile == NULL) { printf("Unable to open file!"); exit(0); } strcpy(person.firstname, "Name", 20); strcpy(person.famname, "surname", 20); strncpy(person.pers_number, "880192234", 13); fwrite(&person, sizeof(PERSON), 1, ptr_myfile); fclose(ptr_myfile); }
你主要会做这个
int main(void) { write_new_file(); search_by_firstname("Neda"); return(0); }
-
您没有为
temp
分配空间,在这里您尝试访问temp
fread(temp,sizeof(PERSON),1,ptr_myfile);
但您并没有为它分配空间,这里也不需要指针,而是
PERSON temp; fread(&temp, sizeof(PERSON), 1, ptr_myfile);
如果做得更好,您可能还想在尝试取消引用
temp
之前检查fread()
是否成功,因为否则会导致未定义的行为。