user2019482
user2019482

Reputation: 21

Cannot delete file in C

I am using Code Blocks and I would like to delete a file using C. The file is used by two functions but not simultaneously.

This is the first function which uses the file:

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;
}

And this is the second function:

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);
}

All the time I am getting the message "Error deleting the file save.txt". Can you please check it out and tell me what am I doing wrong?

Upvotes: 0

Views: 2287

Answers (2)

Ibrar Ahmed
Ibrar Ahmed

Reputation: 1089

Look at this part of the code

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

I think you want this

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

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753615

Your code in the second function contains:

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

You're removing the file twice and the second time it isn't there, so you report failure.

Fix: remove the unchecked remove(buffer) line.

Upvotes: 4

Related Questions