[英]CFile returns debug assertion
我在Visual C ++中有一个旧项目,我正尝试将其迁移到Visual Studio2013。当我验证是否存在txt文件时, CFile
返回调试断言错误。 代码是:
if (!txt_file.Open(txt_name, CFile::modeWrite | CFile::shareDenyWrite | CFile::typeText))
{
//action if the file exists
}
有什么问题,我做错了什么? 谢谢
LE:
txt_file
在类trace
声明为: CStdioFile txt_file
txt_name
在类trace
名为open_file
的方法中声明为: private CString txt_name
方法open_file
包含返回调试断言错误的if语句。
您可能正在使用:
CFile txt_file;
CFile
不支持文本模式。
要以文本模式打开,您可以更改为:
CStdioFile txt_file;
那应该可以解决问题(至少,在这种情况下使用CFile
生成一个断言)。
如果您已经在使用CStdioFile
,则打开模式(的组合)可能存在问题。 作为测试,尝试删除CFile::shareDenyWrite
。 也可能有安全限制。
mfc \\ filecore.cpp行:179
最好是通过调试器逐步解决,或者查看filecore.cpp Line: 179
,查看在那里检查了什么(我会为您查找,但现在没有Visual Studio 2013 -可能是开放模式)。
更新 :
这是第179行:
// shouldn't open an already open file (it will leak)
ASSERT(m_hFile == INVALID_HANDLE_VALUE);
该文件已经打开。 因此,无需再次打开它,或者首先需要关闭,才能以其他打开模式打开。
txt_file.Close();
或测试文件是否打开(对于CMemFile
无效):
if (txt_file.m_hFile != CFile::hFileNull) { // file already open
txt_file.Close();
}
解决了 !
我没有使用问题中的代码来检查文件是否存在,而是使用了以下代码:
CFileStatus sts; //status flag
bool chkifFileExists = CFile::GetStatus(txt_name, sts); // return TRUE if the file exists else return false
if (!(chkifFileExists))
{
//do something
}
谢谢大家的支持!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.