-3

When I run the program and I want to delete a product code then this function deletes all the file.

Could you please help me?

void PRODUCT_delete()
{
    int code;
    FILE *stock=fopen("stock.dat","wb+");

printf("PLEASE TYPE THE CODE OF THE PRODUCT YOU WISH TO DELETE:\t");

scanf(" %d",& code);
printf("\n");

fseek(stock,0,SEEK_END);

int fl_size=ftell(stock);
int quantity= fl_size/sizeof(product);

rewind(stock);

prdct cprd= (product *)malloc (sizeof(product)*quantity);
assert(cprd);

prdct cprd1= (product *) malloc(sizeof(product)*quantity);
assert(cprd1);

fread(cprd1,sizeof(product),quantity,stock);

int i;

for(i=0;i<quantity;i++)
    {
    if(cprd1[i].code!=code)
        {
    cprd[i]=cprd1[i++];

    }
        else
        {
            continue;
    }
     }

 fwrite(cprd,sizeof(product),quantity,stock);

 fclose(stock);
 free(cprd1);
 free(cprd);
 printf("\a THE PRODUCT DELETED!!!\n")
}
Pavel
  • 7,436
  • 2
  • 29
  • 42
Dot
  • 43
  • 1
  • 4

2 Answers2

0

See:

w+ truncate the file. You should use r+

Apparently the b modificator is for windows (non-posix systems).

fjardon
  • 7,921
  • 22
  • 31
0

A few problems:

  1. opening a file with wb+ truncates the file, you should probably use a new file for output and then rename afterwards
  2. <was wrong, deleted>
  3. you need to decrement quantity if you remove the product code
jarmod
  • 71,565
  • 16
  • 115
  • 122
  • 1
    1) I answered to use `r+` which is exactly what the OP wants, no need to use a new file. 2) You CAN copy structs, no need to use memcpy. – fjardon Jun 05 '14 at 18:01