CFile::Open

已重载。 Open 旨在用于默认 CFile 构造函数的使用。

virtual BOOL Open(
   LPCTSTR lpszFileName,
   UINT nOpenFlags,
   CFileException* pError = NULL 
);
virtual BOOL Open(
   LPCTSTR lpszFileName,
   UINT nOpenFlags,
   CAtlTransactionManager* pTM,
   CFileException* pError = NULL
);

参数

  • lpszFileName
    是路径所需文件的字符串。 路径可以是相对路径,绝对或网络名称 (UNC)。

  • nOpenFlags
    定义文件共享和访问模式 UINT。 因此,在打开文件时,它指定该操作。 您可以合并选项使用按位或( |)运算符。 需要一种访问权限和一个股票选择; modeCreatemodeNoInherit 模式是可选的。 对模式的选项列表参见 C文件 构造函数。

  • pError
    要接收失败的操作状态的现有文件异常对象的指针。

  • pTM
    为CAtlTransactionManager对象的指针

返回值

非零,则打开成功;否则为0。 才返回0,pError 参数是有意义的。

备注

两个函数窗体打开的失败是普通的文件,预期的条件一个“安全”方法。

CFile 构造函数都将在出错时的异常,Open 将返回错误条件的 FALSE。 但是Open 仍可以初始化 CFileException 对象描述错误。 如果您没有提供 pError 参数,或者,如果您通过 pError的 NULLOpen 将返回 FALSE 并且不会引发 CFileException。 如果通过指向现有 CFileExceptionOpen 遇到错误,该功能由描述该错误的信息将加载它。 在这两个条件都不用例请将 Open 引发异常。

下表描述 Open的可能结果。

pError

遇到的错误?

返回值

CFileException内容

NULL

TRUE

CFileException的PTR

TRUE

保持不变。

NULL

FALSE

CFileException的PTR

FALSE

初始化描述错误

示例

CFile f;
CFileException e;
TCHAR* pszFileName = _T("Open_File.dat");
if(!f.Open(pszFileName, CFile::modeCreate | CFile::modeWrite, &e))
{
   TRACE(_T("File could not be opened %d\n"), e.m_cause);
}
//A second example for CFile::Open.
//This function uses CFile to copy binary files.
bool BinaryFileCopy(LPCTSTR pszSource, LPCTSTR pszDest)
{
   // constructing these file objects doesn't open them
   CFile sourceFile;
   CFile destFile;

   // we'll use a CFileException object to get error information
   CFileException ex;

   // open the source file for reading
   if (!sourceFile.Open(pszSource,
      CFile::modeRead | CFile::shareDenyWrite, &ex))
   {
      // complain if an error happened
      // no need to delete the ex object

      TCHAR szError[1024];
      ex.GetErrorMessage(szError, 1024);
      _tprintf_s(_T("Couldn't open source file: %1024s"), szError);
      return false;
   }
   else
   {
      if (!destFile.Open(pszDest, CFile::modeWrite |
         CFile::shareExclusive | CFile::modeCreate, &ex))
      {
         TCHAR szError[1024];
         ex.GetErrorMessage(szError, 1024);
         _tprintf_s(_T("Couldn't open source file: %1024s"), szError);

         sourceFile.Close();
         return false;
      }

      BYTE buffer[4096];
      DWORD dwRead;

      // Read in 4096-byte blocks,
      // remember how many bytes were actually read,
      // and try to write that many out. This loop ends
      // when there are no more bytes to read.
      do
      {
         dwRead = sourceFile.Read(buffer, 4096);
         destFile.Write(buffer, dwRead);
      }
      while (dwRead > 0);

      // Close both files

      destFile.Close();
      sourceFile.Close();
   }

   return true;
}

要求

Header: afx.h

请参见

参考

C文件选件类

层次结构图

CFile::CFile

CFile::Close