为什么删除和重命名功能在我的程序中不起作用?

时间:2014-06-07 10:45:47

标签: c

当我尝试使用fowling代码行删除文件时,我得到的结果是在程序结束后存在两个文件(stock.dat和clone.dat)(因此我想只存在重命名为stock.dat(=原始名称为clone.dat))。提前谢谢。

    int code;
    FILE *stock=fopen("stock.dat","rb");
    FILE *stc_clone=fopen("clone.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 prd_pntr= (product *) malloc(sizeof(product)*quantity);
    assert(prd_pntr);

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

    int i;

    for(i=0;i<quantity;i++){

        if(prd_pntr[i].code==code){

            continue;

        }else{

            fprintf(stc_clone,"%d %s %d",prd_pntr[i].code,prd_pntr[i].description,prd_pntr[i].volume);

        }

    }

    fclose(stc_clone);
    fclose(stock);
    remove(stock);
    rename("clone.dat","stock.dat");
    free(prd_pntr);
    printf("\n\a THE PRODUCT DELETED!!!\n");

1 个答案:

答案 0 :(得分:2)

您的函数不会删除该文件,因为您将FILE*而不是char*传递给remove函数:

FILE *stock = fopen("stock.dat","rb");
...
fclose(stock);
remove(stock); // <<== HERE: you are supposed to pass a name, not FILE*

要解决此问题,请更改remove行,如下所示

remove("stock.dat");