无法使用 _wremove API 删除文件(权限问题)

Unable to delete file with _wremove API (permission issue)

我无法从我的 C++ 应用程序中删除临时文件,它因“权限被拒绝”错误而失败。这是代码片段,

void DeleteTempFile(const std::wstring& path) {
    wchar_t* wc = const_cast<wchar_t*>( path.c_str() );
    if( _wremove( wc ) != 0 )
        Log(fatal, std::string("Error: ") + std::strerror(errno) + std::string(" while deleting file: ") + std::string(path.begin(),path.end()));
    else
        Log(fatal, std::string("Successfully deleted file: ") + std::string(path.begin(),path.end()));
}

这是我执行这段代码时得到的日志,
错误:删除文件时权限被拒绝:C:/Windows/SERVIC~1/LOCALS~1/AppData/Local/Temp/abcD12E.pdf

有人可以帮我解决这个权限问题吗?

来自Microsoft docs

remove, _wremove

[...]

Return Value

Each of these functions returns 0 if the file is successfully deleted. Otherwise, it returns -1 and sets errno either to EACCES to indicate that the path specifies a read-only file, specifies a directory, or the file is open, or to ENOENT to indicate that the filename or path was not found.

_wremove 的调用正在返回 EACCES,因为 Permission denied 已打印(检查 errno constants)。所以有3个选项:

  1. 您的文件已打开(您需要在调用 _wremove 之前首先关闭文件)。
  2. 你的路径是一个目录名。
  3. 文件是read-only(您需要更改文件权限)。

它不能是 2(我打赌 abcD12E.pdf 是一个文件)。判断是1还是3,括号里的动作。