0

我在 Visual C++ 中有一个旧项目,我正在尝试将其迁移到 Visual Studio 2013。当我验证 txt 文件是否存在时,CFile返回调试断言错误。代码是:

if (!txt_file.Open(txt_name,    CFile::modeWrite | CFile::shareDenyWrite  | CFile::typeText))
{
    //action if the file exists
}

有什么问题,我做错了什么?谢谢

乐:

txt_fileCStdioFile txt_file在类trace
txt_name中声明为:在类private CString txt_name中命名的方法中声明为: 该方法包含返回调试断言错误的 if 语句。open_filetrace
open_file

4

2 回答 2

0

解决了 !

我没有使用问题中的代码来检查文件是否存在,而是使用了以下代码:

  CFileStatus sts; //status flag
        bool chkifFileExists = CFile::GetStatus(txt_name, sts); // return TRUE if the file exists else return false




        if (!(chkifFileExists))

{
 //do something
}

谢谢大家的支持!

于 2016-01-21T08:41:57.040 回答
0

您可能正在使用:

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();
}
于 2016-01-19T13:57:27.530 回答