我是C初学者。经过许多教程后,我不知道为什么我会得到分段错误。我的函数write_new_file和search_by_firstname都出现了这个错误。我认为问题在于我的函数write_new_file中的参数类型PERSON * inrecord。我已经尝试将其从指针更改为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);
}
答案 0 :(得分:1)
您在
中取消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);
会做得更好,在尝试取消引用fread()
之前,您可能还想检查temp
是否成功,否则会导致未定义的行为。