ofstream 不适用于 Windows 7 隐藏文件 [英] ofstream doesn't work on Windows 7 hidden file
问题描述
我意识到 ofstream
不适用于 Windows 7 隐藏文件.
I realize that ofstream
doesn't work on Windows 7 hidden file.
这是快速测试代码.
#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();
}
这是我得到的输出
ifstream open
ofstream not open!
如果我使用的是FILE_ATTRIBUTE_NORMAL
,ofstream
会成功打开.
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.
如果我们不以管理员身份启动应用程序,必须为启用用户帐户控制 (UAC) 设置否 很重要.操作系统将帮助我们将实际文件写入 C:\Users\yccheok\AppData\Local\VirtualStore\a.txt
而不是受保护的 C:\
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:\
ofstream
在 Windows 7 隐藏文件上是否失败,是预期的行为吗?
Does ofstream
fail on Windows 7 hidden file, is an expected behaviour?
推荐答案
是的.如基础 CreateFile
文档 所述," 如果指定了 CREATE_ALWAYS
和 FILE_ATTRIBUTE_NORMAL
,则 CreateFile
失败并将最后一个错误设置为 ERROR_ACCESS_DENIED
如果文件存在并且具有 FILE_ATTRIBUTE_HIDDEN
或 FILE_ATTRIBUTE_SYSTEM
属性."
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."
或更易读:CreateFile
失败,如果 CREATE_ALWAYS
和 FILE_ATTRIBUTE_NORMAL
被指定,并且文件有 FILE_ATTRIBUTE_HIDDEN
和/或 FILE_ATTRIBUTE_SYSTEM
属性.
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.
碰巧ofstream
像这样调用CreateFile
.
这篇关于ofstream 不适用于 Windows 7 隐藏文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!