ofstream doesn't work on Windows 7 hidden file

柔情痞子 提交于 2019-12-22 06:07:09

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/6530397/ofstream-doesnt-work-on-windows-7-hidden-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!