C - remove() 不会用 char * 删除

C - remove() doesn't delete with char *

我正在尝试使用 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");

有人可以解释一下吗?

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

试试这个:

#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[])