Im a beginner in C. I would like to write and read a binary file, and i reached this so far:
I can my struct to a binary file, and can read.
Problem one: I can only read integers, somehow strings are printed as garbage or random characters.
Problem two: If i run my program, i add some entries to my binary file, then i print all the entries it is working fine (except Problem one), but after i terminate my program and run AGAIN i got Segmentation Fault while i try to read the file.
Please help me, i just cannot move forward.
/* Our structure */
struct rec
{
int max,cost;
char *name;
};
struct rec addNewEntry()
{
//init
char name[256];
int max;
int cost;
//input
printf("Type name: \n");
scanf("%s" , &name) ;
printf("Type guests limit: \n");
scanf("%d", &max);
printf("Type price: \n");
scanf("%d", &cost);
//create record
struct rec record;
record.name = name;
record.max = max;
record.cost = cost;
return record;
}
int main()
{
FILE *ptr_myfile;
//////////////////////////MENU////////////////////////////////
int option=-1;
while(option!=3)
{
printf("\n=== MENU === \n");
printf("\n1. Print all entries");
printf("\n2. Add new entry");
printf("\n3. Exit");
printf("\n");
printf("\nType menu option:");
scanf("%d", &option);
if(option == 1)
{
printf("\n...Printing all entries\n");
int f=open("stadionok.db",O_RDONLY);
if (f<0){ perror("Error at opening the file\n");exit(1);}
struct rec my_record;
while (read(f,&my_record,sizeof(my_record))){ //use write for writing
printf("name: %s \n",my_record.name);
printf("max: %d \n",my_record.max);
printf("cost: %d \n",my_record.cost);
}
close(f);
}
else if(option ==2)
{
printf("\n...Type a new entry\n");
//OPEN AND CHECK
ptr_myfile=fopen("stadionok.db","a");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
//TYPE A NEW ENTRY
struct rec new_stad = addNewEntry();
//WRITE TO FILE
fwrite(&new_stad, sizeof(struct rec), 1, ptr_myfile);
//CLOSE
fclose(ptr_myfile);
printf("Done.\n");
}
}
return 0;
}
E D I T:
I modified just as you suggested and now i got: error: incompatible types in assignment
at:
char name[256];
//input
printf("Type name: \n");
scanf("%s" , &name) ;
struct rec record;
record.name = name; //HERE