gpt4 book ai didi

c++ - 为什么在MFC中创建和写入模式下无法打开隐藏文件?

转载 作者:搜寻专家 更新时间:2023-10-31 01:29:50 25 4
gpt4 key购买 nike

我正在使用 Visual C++ 2010 和 MFC 编写一个小程序。

以下是我的代码:

        CFile MyFile;
CFileException* pException = NULL;
CString strErrorMessage;
// The Test.txt is a hidden file that I created already.
if (!MyFile.Open(_T("E:\\Test.txt"), CFile::modeWrite | CFile::modeCreate, pException))
{
TCHAR lpCause[255];
pException->GetErrorMessage(lpCause, 255);
strErrorMessage += lpCause;
}
// ...
// rewrite the Test.txt
// ...
MyFile.Close();

下面是我的问题:

1.运行代码时出现未处理的异常,如何修改代码使其正常运行?

2.我尝试删除Test.txt隐藏文件属性,它似乎工作正常。我想知道:为什么一个文件(存在)具有文件隐藏属性不能在创建和写入模式下打开?

谢谢。

最佳答案

pException 只是初始化为NULL,没有分配。您应该分配它,或者简单地声明 CFileException exception; 并传递地址 &exception。此外,如果 CFile::Open 失败,请勿尝试关闭文件。

CFile 的文档表示不要对现有文件使用 CFile::modeCreate,因为它会引发异常。推理不完全正确。

在 Visual Studio 15 中,MFC 的 CFile::Open 源代码显示:

// map creation flags
if (nOpenFlags & modeCreate)
{
if (nOpenFlags & modeNoTruncate)
dwCreateFlag = OPEN_ALWAYS;
else
dwCreateFlag = CREATE_ALWAYS;
}
else
dwCreateFlag = OPEN_EXISTING;
...
CreateFile(... nOpenFlags ...)

CFile::modeCreate(没有 modeNoTruncate)在 CreateFile API 中设置标志 CREATE_ALWAYSCreateFile 的 WinAPI 文档说

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. To avoid the error, specify the same attributes as the existing file.

这解释了为什么该函数仅对存在和隐藏的文件失败。

要解决此问题,我们可以添加 modeNoTruncate 以强制执行 OPEN_ALWAYS。如果需要,使用 CFile::SetLength(0) 截断文件。

CFile MyFile;
CFileException exception;
CString strErrorMessage;
CString filename = _T("e:\\Test.txt");

if(MyFile.Open(filename, CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate,
&exception))
{
//SetLength(0) if file needs to truncate
MyFile.SetLength(0);
MyFile.Close();
}
else
{
TCHAR lpCause[255];
exception.GetErrorMessage(lpCause, 255);
strErrorMessage += lpCause;
}

或者,测试旧文件是否存在,如果文件不存在则添加CFile::modeCreate。再次后跟 SetLength(0) 以截断文件。

UINT flags = CFile::modeWrite;
if(!PathFileExists(filename))
flags |= CFile::modeCreate;
if (MyFile.Open(filename, flags, &exception))
{
MyFile.SetLength(0);
MyFile.Close();
}

关于c++ - 为什么在MFC中创建和写入模式下无法打开隐藏文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49186616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com