I realize that ofstream doesn’t work on Windows 7 hidden file.
Here is the quick test code.
#include <fstream>
#include <iostream>
#include <tchar.h>
#include <windows.h>
int main() {
{
std::ifstream file2(_T("c:\\a.txt"));
if (file2.is_open()) {
std::cout << "ifstream open" << std::endl;
} else {
std::cout << "ifstream not open!" << std::endl;
}
}
// SetFileAttributes(_T("c:\\a.txt"), FILE_ATTRIBUTE_NORMAL);
SetFileAttributes(_T("c:\\a.txt"), FILE_ATTRIBUTE_HIDDEN);
{
std::ofstream file(_T("c:\\a.txt"));
if (file.is_open()) {
std::cout << "ofstream open" << std::endl;
} else {
std::cout << "ofstream not open!" << std::endl;
}
}
getchar();
}
Here is the output I am getting
ifstream open
ofstream not open!
If I am using FILE_ATTRIBUTE_NORMAL, ofstream will be opened successfully.
I do not run the program as Administrator. But, I do use the following linker option.

Having to turn No for Enable User Account Control (UAC) is important, if we do not start the application as Administrator. OS will help us to write the actual file to C:\Users\yccheok\AppData\Local\VirtualStore\a.txt instead of protected C:\
Does ofstream fail on Windows 7 hidden file, is an expected behaviour?
Yes. As noted in the underlying
CreateFiledocumentation, ” IfCREATE_ALWAYSandFILE_ATTRIBUTE_NORMALare specified,CreateFilefails and sets the last error toERROR_ACCESS_DENIEDif the file exists and has theFILE_ATTRIBUTE_HIDDENorFILE_ATTRIBUTE_SYSTEMattribute.”Or more readable:
CreateFilefails if bothCREATE_ALWAYSandFILE_ATTRIBUTE_NORMALare specified, and if the file has theFILE_ATTRIBUTE_HIDDENand/orFILE_ATTRIBUTE_SYSTEMattribute.It just so happens that
ofstreamcallsCreateFilelike this.