arrays - c program.Issue with adding record into text file -



arrays - c program.Issue with adding record into text file -

i'm having problem adding new records in sequential access file. when user enters model code, programme supposed check , display entry same name exists if duplicate had been found. when run code, shows:

record exists record exists record exists record exists

when: 1.the code exists in file 2.the code not exist in file.

can help me this. help appreciated.

//function add together record void stockentry(){ file *fp; fp = fopen("stock.txt","a+"); //fopen opens file.exit programme if unable create file if(fp==null){ puts("file not opened"); }//ends if //obtains info user else{ printf("\nenter model code,model name,cost,price , quantity(use space separate inputs)\n"); scanf("%s %s %f %f %d",code,a.name,&a.cost,&a.price,&a.quantity); rewind (fp); do{ if(strcmp(code,a.code)!=0){ //write details stock.txt fprintf(fp,"%s %s %.2f %.2f %d\n",a.code,a.name,a.cost,a.price,a.quantity); } else{ printf("record exists\n"); } }while(fscanf(fp,"%s %s %f %f %d\n",a.code,a.name,&a.cost,&a.price,&a.quantity)==5); } //fclose closes file fclose(fp); }

you're using do...while loop, compare info before has been read file; first time through, you're comparing old value of a.code. also, you're writing info in middle of file, , see no guarantee records same length.

also, you're using a hold both info got user, , info read file. want 2 structures, 1 each purpose.

i'm not sure why gives record exists, loop should give results want. (i didn't compile or test it, off top of head.)

int exists; struct ... curr; ... scanf("%s %s %f %f %d", curr.code, curr.name, &(curr.cost), &(curr.price), &(curr.quantity)); exists = 0; rewind(fp); while (fscanf(fp, "%s %s %f %f %d\n", a.code, a.name, &(a.cost), &(a.price), &(a.quantity)) == 5) { if (strcmp(curr.code, a.code) == 0) { printf("record exists\n"); exists = 1; break; } } /* @ point, either exists == 1, in case we're @ unknown point in file , wish nothing, or exists == 0, in case we're @ end of file , wish write new record. */ if (exists) fprintf(fp, "%s %s %.2f %.2f %d\n", curr.code, curr.name, curr.cost, curr.price, curr.quantity);

c arrays

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -