I am a C beginner. After going through many tutorials I am not sure why am I getting the segmentation fault. I get this error on both my functions write_new_file and search_by_firstname. I think the problem lies within the argument type PERSON *inrecord in my function write_new_file. I have already tried changing it from a pointer to inrecord and changed all variables accordingly but the problem still existed. I have asked fellow class mates and no solution yet.
//------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);
}
You derefernce a NULL
pointer, in
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);
}
you don't need to pass a pointer to the write file function, what you need is
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);
}
and in your main you would do this
int main(void) {
write_new_file();
search_by_firstname("Neda");
return(0);
}
You don't allocate space for temp
, here you attempt to access temp
fread(temp,sizeof(PERSON),1,ptr_myfile);
but you didn't allocate space for it, you don't need pointer here either, instead
PERSON temp;
fread(&temp, sizeof(PERSON), 1, ptr_myfile);
would do a better job, you might also want to check that you fread()
succeeded, before trying to dereference temp
because otherwise it will lead to undefined behavior.