C - remove()不会删除char *

时间:2016-04-16 18:24:18

标签: c delete-file

我正在尝试删除带有remove()的文件,并且由于某种原因,当我在char *中给它路径时它不起作用。 这就是我所拥有的:

#include<stdio.h>

int main(int argc, char *argv[]){ 

    const char * toDie = "/home/User/Desktop/todie.txt";

    int status = remove(toDie);

    if( status != 0 ){
        printf("Unable to delete the file\n");
    }
}

使用

运行时效果很好
 int status = remove("/home/User/Desktop/todie.txt");

有人可以对此有所了解吗?

1 个答案:

答案 0 :(得分:0)

您应首先检查该文件是否存在,或者是否为该文件提供正确的路径或正确的名称。

试试这个:

#include<stdio.h>
#include<stdlib.h>

int main(void){

    const char * toDie = "/home/User/Desktop/todie.txt";

    FILE *check = fopen(toDie, "r");

    if(!check){
        printf("There is no file with that name\n");

    }

    int status = remove(toDie);

    if( status != 0 ){
        printf("Unable to delete the file\n");
        exit(1);
    }else{
        printf("File removed successfully");
    }
}

可能你注意到我改变了:

int main(int argc, char *argv[]){}

使用:

int main(void){}

因为,如果你运行没有参数的程序,那么就不需要:

(int argc, char *argv[])