我正在尝试使用 DeleteFile()
函数,并在下面编写了程序。
#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;
}
但程序没有按预期运行。创建的文件没有被删除。
输出是:
fail
最佳答案
您使用 fopen
打开了文件,并且在使用 fclose
关闭它之前调用了 DeleteFile
。
正如您可以从 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).
另请注意,在失败时,您可以在 DeleteFile
之后调用 GetLastError
以获取包含有关失败原因的更多信息的错误代码。
关于c++ - DeleteFile() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41878839/