Reputation: 71
I was trying the DeleteFile()
function, and I wrote the program below.
#include <iostream>
#include <fstream>
#include <windows.h>
using namespace std;
int main(){
FILE * filetxt;
// creat a file
filetxt = fopen("C:\\Users\\Thomas\\Desktop\\filetxt.txt", "w");
// delete the file
if (DeleteFile("\\\\.\\C:\\Users\\Thomas\\Desktop\\filetxt.txt") != 0){
cout<<"success";
}else{
cout<<"fail";
}
cin;
}
But the program didn't work as it was supposed to. The file created wasn't deleted.
The output is:
fail
Upvotes: 2
Views: 6952
Reputation: 43044
You opened the file with fopen
and you called DeleteFile
before closing it with fclose
.
As you can read from DeleteFile
MSDN documentation:
The DeleteFile function fails if an application attempts to delete a file that has other handles open for normal I/O or as a memory-mapped file (FILE_SHARE_DELETE must have been specified when other handles were opened).
Note also that, on failure, you can call GetLastError
after DeleteFile
to get an error code with more information about the cause of the failure.
Upvotes: 10