std :: ofstream在拒绝权限的C ++上不显示错误 [英] std::ofstream dont show error on permission denied C++

查看:162
本文介绍了std :: ofstream在拒绝权限的C ++上不显示错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当路径="c:\"时,以下代码未写入文件c:\ err.txt,因为权限被拒绝.但是它不会同时产生错误.而是输出"OK".

The following code when path = "c:\" doesn't write to file c:\err.txt because permission is denied. But it doesn't generate an error at the same time. Rather, it outputs "OK".

如何检查权限是否允许写入?

How I can check whether the permissions would allow the write?

#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;
}

推荐答案

我会说您的代码可以正常工作,并且写操作实际上已经完成,但是为此,也请在写操作之后添加一个检查:

I'd say your code works and the write operation is actually done, but for the sake of it, add a check after the write too:

outfile << err_line << endl;
if(outfile.fail()) cout << "Error3\n";
else cout<<"OK";

在我的系统上,如果未打开文件以成功写入,我会得到您的Error 1 ... can't open file.

On my system, I'll get your Error 1 ... can't open file if the file isn't opened for writing successfully.

还是在运行Windows且Compatibility Files虚拟化仍处于活动状态?如果是这样,则该文件可能会位于 Virtual Store 中,而不是在真实的C:\err.txt路径中.

Or are you running Windows with Compatibility Files virtualization still active? If so, the file will probably be in the Virtual Store, not in the real C:\err.txt path.

示例:C:\Users\username\AppData\Local\VirtualStore

如果在此找到它,那么您可能还会在其中找到很多其他东西.至少在几年前,我遇到类似的问题时就做了.我决定手动(具有管理员权限)将一些较旧的程序存放在其中的几个重要文件移到那里,然后关闭虚拟存储.我现在找不到如何简单地关闭文件和注册表虚拟化的良好且简单的Microsoft官方链接,所以也许可以这样做:

If you find it there, you may find a lot of other stuff in there too. At least I did years ago when I had a similar problem. I decided to manually move (with admin rights) the few important files that some of my older programs had put there and then turn Virtual Store off. I can't find a good and simple official Microsoft link for how to turn off file and registry virtualization right now so perhaps this will do:

RegEdit: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\ 创建一个名称为EnableVirtualizationDWORD键,并为其赋予值0.如果该键已经存在,但设置为非零值,则将其更改.

Reg HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\ Create a DWORD Key with the name EnableVirtualization and give it the value 0. If the key is already there, but set to something else than zero, change it.

这里还有更多: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆