简体   繁体   中英

ofstream doesn't work on Windows 7 hidden file

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM