简体   繁体   English

如何动态分配 CFile 类型的变量? (C++,CFile,新)

[英]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 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 https://msdn.microsoft.com/en-us/library/hwbccf8z.aspx


I used the method of CFile, Open, in the second code.我在第二个代码中使用了CFile,Open的方法。

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.它可以正常工作,而且我认为变量 pImgFile 很好地指向了文件的地址。

In general there is no need to create a CFile on the heap.一般来说,不需要在堆上创建CFile There are several constructors of CFile : 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.第四个和第五个构造函数在内部调用Open So they do open the file.所以他们确实打开了文件。

The other problem is that you should use operator |另一个问题是您应该使用operator | not ||不是|| to combine open flags.组合打开的标志。

I'd suggest using the default CFile constructor and then call Open .建议使用默认的 CFile 构造函数,然后调用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.请注意,如果出现错误,它不会抛出异常(而是返回FALSE ),并且您不需要在它周围放置try/catch Optionally you can also pass CFileException* to Open to get more information if it fails.或者,您还可以将CFileException*传递给Open以在失败时获取更多信息。

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

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