我在Visual C++中有一个旧项目,我正在尝试将其迁移到Visual Studio2013。当我验证txt文件是否存在时,CFile返回调试断言错误。代码是:
if (!txt_file.Open(txt_name, CFile::modeWrite | CFile::shareDenyWrite | CFile::typeText))
{
//action if the file exists
}有什么问题,我做错了什么?谢谢
L.E.:
在类trace中,txt_file被声明为:CStdioFile txt_file
在类trace中名为open_file的方法中,txt_name被声明为:private CString txt_name
方法open_file包含返回调试断言错误的if语句。
发布于 2016-01-19 21:57:28
您可能正在使用:
CFile txt_file;CFile不支持文本模式。
要在文本模式下打开,可以更改为:
CStdioFile txt_file;这应该可以解决这个问题(至少,在本例中使用CFile会生成一个断言)。
如果您已经在使用CStdioFile,那么可能是打开模式(组合)有问题。作为测试,尝试删除CFile::shareDenyWrite。也可能会有安全限制。
mfc\filecore.cpp线路: 179
最好是使用调试器逐步检查一下,或者查看一下filecore.cpp Line: 179,看看在那里检查了什么(我会帮你查一查,但现在手头不要有Visual Studio2013--可能是开放模式)。
更新
这是第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();
}发布于 2016-01-21 16:41:57
解决了!
我没有使用问题中的代码片段来检查文件是否存在,而是使用了以下代码:
CFileStatus sts; //status flag
bool chkifFileExists = CFile::GetStatus(txt_name, sts); // return TRUE if the file exists else return false
if (!(chkifFileExists))
{
//do something
}感谢大家的支持!
https://stackoverflow.com/questions/34878481
复制相似问题