Monday, 15 June 2015

c - Structure data written into file is not being read correctly -



c - Structure data written into file is not being read correctly -

printitems() printing first entered item. when take update item details have been updating in file printitems() not displaying updated ones.

struct canteen { char itemid[15]; char name[15]; int price; }; void printitems() { file *fp1; fp1=fopen("items.txt","r"); struct canteen c; printf("\t%-15s%-30s%-5s\n","item id","item name","price"); while(fread(&c,sizeof(struct canteen),1,fp1)!=null) { printf("\t%-15s%-30s%-5d\n",c.itemid,c.name,c.price); } fclose(fp1); } int updateitem(char id[]) { file *fp; int pos=0; fp=fopen("items.bin","r+"); int found=0; struct canteen b; while(fread(&b,sizeof(struct canteen),1,fp)!=null) { pos=ftell(fp); if(strcmp(b.itemid,id)==0) { found=1; fseek(fp,-sizeof(struct canteen),1); printf("enter new item id: "); scanf("%s",b.itemid); printf("enter new item name: "); scanf("%s",b.name); printf("enter new item cost : "); scanf("%d",&b.price); fwrite(&b,sizeof(struct canteen),1,fp); fclose(fp); break; } } fclose(fp); if(found==1) homecoming 1; else { homecoming 0; } } void main() { file *fp1; file *fp2; char s[1]; char choice[1]; char id[15]; int n,i,j; printf("enter number of items\n"); scanf("%d",&n); fp1=fopen("items.bin","w"); struct canteen c; for(i=0;i<n;i++) { printf("enter item %d id : ",i+1); scanf("%s",c.itemid); printf("enter item %d name : ",i+1); scanf("%s",c.name); printf("enter item %d cost : ",i+1); scanf("%d",&c.price); fwrite(&c,sizeof(struct canteen), 1, fp1); } fclose(fp1); printf("item details stored file items.txt\n"); printitems(); while(1) { printf("do want update items?\n come in y or n : "); scanf("%s",s); if(s[0]!='n') { printf("enter item id: "); scanf("%s",id); if(!updateitem(id)) printf("no item found id: %s",id); else { printf("item detials after updation.\n"); printitems(); } } else break; } getch(); }

printitems() printing first entered item. when take update item details have been updating in file printitems() not displaying updated ones.

c

No comments:

Post a Comment