当 path = "c:\"时,以下代码不会写入文件 c:\err.txt,因为权限被拒绝。但它不会同时产生错误。相反,它输出“OK”。
我如何检查权限是否允许写入?
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
bool writeLineToErr(string path, string err_line){
std::ofstream outfile(path+"err.txt", std::ios_base::app);
if(!outfile){
cout<<"Error 1 "+path+"err.txt"+" can't open file!";
return false;
}
if(outfile.fail()){
cout<<"Error 2 "+path+"err.txt"+" can't open file!";
return false;
}
outfile << err_line << endl;
cout<<"OK";
outfile.close();
return true;
}
int main(int argc, char** argv) {
writeLineToErr("c:\\","Some Line");
return 0;
}
最佳答案
我会说您的代码有效并且写入操作实际上已经完成,但是为了它,在写入之后也添加一个检查:
outfile << err_line << endl;
if(outfile.fail()) cout << "Error3\n";
else cout<<"OK";
在我的系统上,我会得到你的
Error 1 ... can't open file
如果未打开文件以成功写入。编辑:或者你是用
Compatibility Files
运行 Windows 吗?虚拟化仍然活跃?如果是这样,该文件可能会在虚拟存储中,而不是在真正的 C:\err.txt
中。小路。示例:
C:\Users\username\AppData\Local\VirtualStore
如果你在那里找到它,你可能也会在那里找到很多其他的东西。至少我在几年前遇到类似问题时做过。我决定手动移动(使用管理员权限)我的一些旧程序放在那里的几个重要文件,然后关闭虚拟商店。我找不到关于如何 的良好且简单的 Microsoft 官方链接关闭文件和注册表虚拟化现在所以也许这会做:
注册编辑:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\
创建 DWORD
名称为 EnableVirtualization
的 key 并给它值0
.如果 key 已经存在,但设置为非零,请更改它。这里还有更多:
UAC Group Policy Settings and Registry Key Settings
关于c++ - 当权限被拒绝 C++ 时,std::ofstream 不显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53526601/