无法删除C中的文件

时间:2013-03-12 19:56:10

标签: c file delete-file

我正在使用代码块,我想使用 C 删除文件。该文件由两个函数使用,但不能同时使用。

这是第一个使用该文件的函数:

double FileRead()
{
    double n,cl,cd,result;
    FILE *fd;
    char filename[] = "save.txt";
    char buff[5024];


    if ((fd = fopen(filename, "r")) != NULL)
    {
        fseek(fd, 0, SEEK_SET);
        while(!feof(fd))
        {
            memset(buff, 0x00, 5024);
            fscanf(fd, "%[^\n]\n", buff);
        }
         sscanf(buff, "%lf %lf %lf",&n,&cl,&cd);
         printf("cl: %1.5f  cd: %1.5f\n",cl,cd);


    result = (cl/cd);
    printf("The CL/CD ratio is : %1.5f\n",result);
    }
    else
        result = 0;

        fclose(fd);

    return result;
}

这是第二个功能:

void evaluate(void)  /*evaluate the population */
{
    int mem;
    int i;
    double x[NVARS+1];
    char buffer[101] = "save.txt";

    FILE *controlpoints;

     double y[NVARS] = {1.00000,0.92544,0.82351,0.78301,0.74004,0.50199,0.40422,0.31056,        /*fixed values on x axis */
     0.18549,0.14954,0.11702,0.06331,0.02581,0.01334,0.00509,0.00000,0.00052,0.00555,0.03324,
     0.11345,0.33088,0.43678,0.60146,0.70751,0.8043,0.92047,0.98713,1.00000};



    for(mem = 0; mem < POPSIZE; mem++)
    {
        controlpoints = fopen("controlpoints2.txt","w");

        for(i = 0; i < NVARS; i++)
        {
           x[i+1] = population[mem].gene[i];

           fprintf(controlpoints,"%1.5f\n%1.5f\n",y[i],x[i+1]);

            printf("The value of population[%d].gene[%d] is %f\n",mem,i,population[mem].gene[i]);

        }

        fclose(controlpoints);
        rbspline();

        XfoilCall();

        population[mem].fitness = FileRead();

    }

  remove(buffer);
        if(remove(buffer) == 0)
          printf("File %s  deleted.\n", buffer);
        else
          fprintf(stderr, "Error deleting the file %s.\n", buffer);
}

我一直收到消息“删除文件save.txt时出错”。你可以看看它,告诉我我做错了什么吗?

2 个答案:

答案 0 :(得分:4)

第二个函数中的代码包含:

remove(buffer);
    if (remove(buffer) == 0)
        printf("File %s deleted.\n", buffer);
    else
        fprintf(stderr, "Error deleting the file %s.\n", buffer);

您要删除文件两次,第二次不存在,因此您报告失败。

修复:删除未经检查的remove(buffer)行。

答案 1 :(得分:1)

查看代码的这一部分

  remove(buffer);
    if(remove(buffer) == 0)
      printf("File %s  deleted.\n", buffer);
    else

我想你想要这个

ret=remove(buffer);
if(ret==0)
      printf("File %s  deleted.\n", buffer);
else