std::ofstream dont show error on permission denied C++

a 夏天 提交于 2019-12-14 02:43:58

问题


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

回答1:


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";

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

Edit: 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.

Example: C:\Users\username\AppData\Local\VirtualStore

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\ 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.

There's more here: UAC Group Policy Settings and Registry Key Settings



来源:https://stackoverflow.com/questions/53526601/stdofstream-dont-show-error-on-permission-denied-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!