i dont know what is the problem, it simply dont write the struct to the file =(
Code:#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> struct restaurant { char *name; }; struct llist_node { struct restaurant *data; struct llist_node *next; }; struct llist { struct llist_node *head; }; int llist_load(struct llist *list, char *path){ int append(struct llist *list, struct restaurant *temp); struct restaurant *temp; FILE *file = fopen(path,"rb"); if (file != NULL){ while(temp=malloc(sizeof(struct restaurant)), fread(temp, sizeof(struct restaurant), 1, file) != (size_t)NULL){ printf("%d",temp->name); append(list,temp); } free(temp); fclose(file); } return 1; } int llist_save(struct llist *list, char *path){ struct llist_node *node; FILE *file = fopen(path,"w+"); if(list->head == NULL || file == NULL) return 0; node = list->head; while(node != NULL){ printf("%s %d",*(node->data),sizeof(struct restaurant)); fwrite((*node).data, sizeof(struct restaurant), 1 , file); node = node->next; } fclose(file); return 1; } int main(void){ char buffer[256]; int append(struct llist *list, struct restaurant *temp); void output(struct llist *list); struct restaurant *input(void); char path[] = "data.dat"; int option; struct llist *list = malloc(sizeof(*list)); list->head = NULL; llist_load(list,path); do { printf("Menu\n1: Add\n2: View All\n3: Search\n4: Save\n0: Exit\n\nOption: "); fgets(buffer,sizeof(buffer),stdin); sscanf (buffer,"%d",&option); if(option == 1) append(list,input()); else if(option ==2) output(list); else if (option==4) { if(llist_save(list, path) == 1) printf("Save successful.\n"); else printf("Can't save.\n"); } } while(option); return(0); } int append(struct llist *list, struct restaurant *temp){ struct llist_node *node; struct llist_node *new1 = malloc(sizeof(*new1)); if(list->head != NULL){ node = list->head; while(node->next != NULL){ node=node->next; } node->next=new1; } else{ list->head=new1; } new1->next = NULL; new1->data = temp; return 1; } struct restaurant *input(void) // Introdução de novo contacto { char buffer[256]; struct restaurant *temp = malloc(sizeof(*temp)); fgets(buffer,sizeof(buffer),stdin); temp->name = malloc(strlen(buffer)+1); buffer[strlen(buffer)-1]=0; strcpy(temp->name,buffer); return temp; } void output(struct llist *list) { struct llist_node *node; node = list->head; while(node != NULL){ printf("Name: %s\n",node->data->name); node = node->next; } }



LinkBack URL
About LinkBacks


