1

Inside one of my functions that are being called by the main(), I have the following very simple testing snippet.

ofstream outFile;
outFile.open("C:\\Program Files\\data\\test.txt");
outFile << "test\n";
outFile.close();

After running the code, I didn't see the file appears. Why is it so?

Sibbs Gambling
  • 19,274
  • 42
  • 103
  • 174

1 Answers1

3

Unfortunately C++ does not specify any way to get more detailed error. See Get std::fstream failure error messages and/or exceptions.

But the platform-specific interface should work. After each operation check whether outFile.bad() and if it is true, check GetLastError(). Interpret according to appropriate table in documentation or using FormatMessage.


I would suspect the problem is permissions. Windows Vista introduced this "user access control" that should pop up a dialog whenever program wants to do something that requires administrator privileges even if the current user has them. The problem is that the dialog only pops up under certain conditions. Notably it will not pop up for console applications and the application is denied permissions right away. Such application has to be explicitly executed "as administrator". Of course don't forget being able to write particular file there does not imply being able to create a new one.

Community
  • 1
  • 1
Jan Hudec
  • 73,652
  • 13
  • 125
  • 172
  • On Windows, what is the status of `errno`? Does it give you less (more?) information than `GetLastError()`? It would be nice to use it as a platform-independent alternative. But I don't know if `strerror_r` exists on Windows (since I don't think `strerror_s` exists on Unix). – Adrian Ratnapala Oct 09 '13 at 14:37
  • @AdrianRatnapala: IIRC `GetLastError()` distinguishes some cases that `errno` does not. And `errno` is implemented in terms of `GetLastError()` on windows anyway. – Jan Hudec Oct 09 '13 at 14:45
  • Does that mean that if I wanted to write something cross-platform, then using `errno` only would not suck very much? Appart from the `strerror_[rs]` issue that is. – Adrian Ratnapala Oct 09 '13 at 20:01
  • @AdrianRatnapala: I believe errno should do, yes, but I have not tried it myself (I am working on cross-platform application, but we have platform-specific code using native windows APIs, also because windows was first platform and because WinCE don't have the unix APIs). – Jan Hudec Oct 10 '13 at 05:36