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. 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 :
txt_file
is declared as : CStdioFile txt_file
in the class trace
txt_name
is declared as : private CString txt_name
in the method named open_file
from class trace
The method open_file
contains the if statement that returns debug assertion error.
You are probably using:
CFile txt_file;
CFile
does not support text mode.
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).
If you are using CStdioFile
already, there's probably a problem with the (combination of) open modes. As a test, try to remove CFile::shareDenyWrite
. There could be security restrictions too.
mfc\\filecore.cpp Line: 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).
Update :
This is line 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
):
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 !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.