Aleksandrs Kantajevs
Aleksandrs Kantajevs

Reputation: 43

std::ofstream does not show error when permission denied C++

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

Upvotes: 2

Views: 2276

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

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

Upvotes: 1

Related Questions