c++ - DeleteFile() 不工作

标签 c++ c winapi

我正在尝试使用 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/

相关文章:

c++ - 如何用 C++ 像 Java 一样表达匿名方法重写?

c++ - Qt C++ .arg 字符串错误

c - 不知道如何使用 tcsetpgrp()

c++ - 英特尔引脚 : how to detect realloc size

c++ - 如何使用两个独立的语法实现计算机语言翻译器

c++ - “数据”未在此范围内声明

c - 警告 : pointer argument of a function may be used uninitialized

c++ - 在屏幕上快速绘制自定义格式图像

windows - 使用文件识别进程

c++ - RegisterClassEx 崩溃 - C++