Delete files from a specific folder in C

巧了我就是萌 提交于 2019-12-04 06:15:58

问题


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. I tried the same approach as my displayDIR() function to change directory but I can't figure out how to make it work. I use cygwin as compiler.

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

回答1:


You need to include the folder path in the argument to remove():

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


来源:https://stackoverflow.com/questions/22003586/delete-files-from-a-specific-folder-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!