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