Search code examples
c++mfccfile

How can I dynamically allocate a CFile type of variable? (C++, CFile, new)


static TCHAR BASED_CODE szFilter[] = _T("YUV Files|*.yuv|")
CFileDialog fileDlg(TRUE, _T("yuv"), _T("bus.yuv"), OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, szFilter);
if (fileDlg.DoModal() == IDOK)
{
    CString pathName = fileDlg.GetPathName();
    CFile* pImgFile = NULL;
    pImgFile = new CFile(pathName, CFile::modeRead || CFile::typeBinary);
}

I refer to an example in the following site. https://msdn.microsoft.com/en-us/library/b569d0t4.aspx

static TCHAR BASED_CODE szFilter[] = _T("YUV Files|*.yuv|")
CFileDialog fileDlg(TRUE, _T("yuv"), _T("bus.yuv"), OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, szFilter);
if (fileDlg.DoModal() == IDOK)
{
    CString pathName = fileDlg.GetPathName();
    CFile imgFile;
    CFileException e;
    if (!imgFile.Open(pathName, CFile::modeRead || CFile::typeBinary, &e))
    {
        TRACE(_T("File could not be opened %d\n"), e.m_cause);
    }
}

I refer to the first example in the following site. https://msdn.microsoft.com/en-us/library/hwbccf8z.aspx


I used the method of CFile, Open, in the second code.

For the upper code, how can I open the file?

When I use dynamic allocation, is it automatically open the file?

imgLength = pImgFile->GetLength();
CString str;
str.Format(_T("Your SYSTEM.INI file is %I64u bytes long."), imgLength);
AfxMessageBox(str); 

I tried to append this code to the first code.

It works without any problems, and I think the variable, pImgFile, points the address of the file well.


Solution

  • In general there is no need to create a CFile on the heap. There are several constructors of CFile:

    CFile( );
    CFile(
       CAtlTransactionManager* pTM
    );
    CFile(
       HANDLE hFile 
    );
    CFile(
       LPCTSTR lpszFileName,
       UINT nOpenFlags 
    );
    CFile(
       LPCTSTR lpszFileName,
       UINT nOpenFlags,
       CAtlTransactionManager* pTM
    );
    

    The fourth and the fifth constructors call Open internally. So they do open the file.

    The other problem is that you should use operator | not || to combine open flags.

    I'd suggest using the default CFile constructor and then call Open. Please note that it wont throw an exception in case of error (returns FALSE instead) and you wont need to place try/catch around it. Optionally you can also pass CFileException* to Open to get more information if it fails.