简体   繁体   English

CFile返回调试断言

[英]CFile returns debug assertion

I have an old project in Visual C++ and I'm trying to migrate it to Visual Studio 2013. When I verify if a txt file exists, CFile returns debug assertion error. 我在Visual C ++中有一个旧项目,我正尝试将其迁移到Visual Studio2013。当我验证是否存在txt文件时, CFile返回调试断言错误。 The code is: 代码是:

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

What is the problem, I'm doing something wrong ? 有什么问题,我做错了什么? Thank you 谢谢

LE : LE:

txt_file is declared as : CStdioFile txt_file in the class trace txt_file在类trace声明为: CStdioFile txt_file
txt_name is declared as : private CString txt_name in the method named open_file from class trace txt_name在类trace名为open_file的方法中声明为: private CString txt_name
The method open_file contains the if statement that returns debug assertion error. 方法open_file包含返回调试断言错误的if语句。

You are probably using: 您可能正在使用:

CFile txt_file;

CFile does not support text mode. CFile不支持文本模式。

To open in text mode, you can change to: 要以文本模式打开,您可以更改为:

CStdioFile txt_file;

That should fix the problem (at least, using CFile in this case generates an assertion). 那应该可以解决问题(至少,在这种情况下使用CFile生成一个断言)。


If you are using CStdioFile already, there's probably a problem with the (combination of) open modes. 如果您已经在使用CStdioFile ,则打开模式(的组合)可能存在问题。 As a test, try to remove CFile::shareDenyWrite . 作为测试,尝试删除CFile::shareDenyWrite There could be security restrictions too. 也可能有安全限制。

mfc\\filecore.cpp Line: 179 mfc \\ filecore.cpp行:179

It might be best to step through it with the debugger, or have a look at filecore.cpp Line: 179 to see what gets checked there (I would look it up for you, but don't have Visual Studio 2013 at hand right now - probably open modes). 最好是通过调试器逐步解决,或者查看filecore.cpp Line: 179 ,查看在那里检查了什么(我会为您查找,但现在没有Visual Studio 2013 -可能是开放模式)。

Update : 更新

This is line 179: 这是第179行:

// shouldn't open an already open file (it will leak)

ASSERT(m_hFile == INVALID_HANDLE_VALUE);

The file is already opened. 该文件已经打开。 So no need to open it again, or first needs to be closed, to open with other open modes. 因此,无需再次打开它,或者首先需要关闭,才能以其他打开模式打开。

txt_file.Close();

Or to test if the file is open (not valid for CMemFile ): 或测试文件是否打开(对于CMemFile无效):

if (txt_file.m_hFile != CFile::hFileNull) { // file already open
    txt_file.Close();
}

SOLVED ! 解决了 !

Instead of using the piece of code from the question to check if the file exists, I've used the following code : 我没有使用问题中的代码来检查文件是否存在,而是使用了以下代码:

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




        if (!(chkifFileExists))

{
 //do something
}

Thank you all for your support ! 谢谢大家的支持!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM