Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ofstream doesn't work on Windows 7 hidden file

Tags:

c++

windows-7

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.

linker options

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?

like image 935
Cheok Yan Cheng Avatar asked Jun 30 '11 05:06

Cheok Yan Cheng


1 Answers

Yes. As noted in the underlying CreateFile documentation, " If CREATE_ALWAYS and FILE_ATTRIBUTE_NORMAL are specified, CreateFile fails and sets the last error to ERROR_ACCESS_DENIED if the file exists and has the FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_SYSTEM attribute."

Or more readable: CreateFile fails if both CREATE_ALWAYS and FILE_ATTRIBUTE_NORMAL are specified, and if the file has the FILE_ATTRIBUTE_HIDDEN and/or FILE_ATTRIBUTE_SYSTEM attribute.

It just so happens that ofstream calls CreateFile like this.

like image 177
MSalters Avatar answered Oct 15 '22 22:10

MSalters