开发者

ofstream doesn't work on Windows 7 hidden file

开发者 https://www.devze.com 2023-03-16 20:58 出处:网络
I realize that ofstream doesn\'t work on Windows 7 hidden file. Here is the quick test code. #include <fstream>

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(开发者_StackOverflow中文版"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.

ofstream doesn't work on Windows 7 hidden file

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消