简体   繁体   English

从C中的特定文件夹删除文件

[英]Delete files from a specific folder in C

I'm trying to delete files from a specifc folder. 我正在尝试从特定文件夹中删除文件。 My deleteFile() function only deletes on its home folder, not on /tmp folder which is what I need. 我的deleteFile()函数仅在其主文件夹中删除,而不在我需要的/tmp文件夹上删除。 I tried the same approach as my displayDIR() function to change directory but I can't figure out how to make it work. 我尝试了与displayDIR()函数相同的方法来更改目录,但是我不知道如何使其工作。 I use cygwin as compiler. 我使用cygwin作为编译器。

void deleteFile() {
    int status;
    char filetodelete[25];

    printf("\n \t **Delete File**\n");

    displayDIR();

    printf("\n\tChoose the name of the file to delete:\t");
    scanf("%s", filetodelete);

    status = remove(filetodelete);
    if( status == 0 )
        printf("%s file deleted successfully.\n",  filetodelete);
    else {
        printf("\n\tUnable to delete the file");
        perror("\n\tError");
    }
}


void displayDIR() {
    DIR           *d;
    struct dirent *dir;
    d = opendir("C:/cygwin/tmp");
    if (d) {
        while ((dir = readdir(d)) != NULL)
             printf("\t\t\t%s\n", dir->d_name);

        closedir(d);
    }
}

You need to include the folder path in the argument to remove() : 您需要在remove()的参数中包含文件夹路径:

char fullpath[40] = "C:/cygwin/tmp/";
strcat(fullpath, filetodelete);
status = remove(fullpath);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM