开发者

Problem with using function remove(..) from stdio.h C++

开发者 https://www.devze.com 2023-03-12 06:12 出处:网络
Hello my question is why the following function fails to delete the file whose name is specified in dir1;

Hello my question is why the following function fails to delete the file whose name is specified in dir1; I use the function remove but it seems that there is some kind of a problem with it. Please help me.

#include <stdio.h>
void test(char* dir1,char* dir2)
{

  开发者_如何学Python  FILE * file1,* file2;
    file1=fopen(dir1,"r");
    file2=fopen(dir2,"w");
    if(!file1){ return;}
    int inpch;
    char* string = new char[10];
    string[9]='\0';
    int br=0;

    do
    {   

        while((inpch=fgetc(file1))!=EOF)
        {
            string[br]=char(inpch);
            br++;
            if(br==9)break;
        }


        if(br!=9)
        {
            string[br]='\0';
            fputs(string,file2);


            return;
        }
        else
        {   
            fputs(string,file2);
            br=0;

        }


    }while(true);

    fclose(file1);
    remove(dir1);/// I DON"T UNDERSTAND WHY IT DOESN"T DELETE THE FILE.
    fclose(file2);
}


I guess at some point before exiting the do-while loop, the following if condition becomes true, and the function returns before it reaches to the end of the function, without even calling the remove function.

    if(br!=9)
    {
        string[br]='\0';
        fputs(string,file2);
        return; //<------------ here you're returning!
    }

Did you want to write return or break? Looks like its there the problem lies.


Why don't you check for the return value and error code (errno) that tells you exactly why the function didn't succeed?


Replace your remove call with this :

if( remove( "myfile.txt" ) != 0 )
    perror( "Error deleting file" );
  else
    puts( "File successfully deleted" );

and it should tell you what happened.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号