CFile::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 。在開啟檔案時,它會指定要執行的動作。您可以合併選項使用位元 OR (|) 運算子。需要一個存取權限和一個共用選項, modeCreatemodeNoInherit 模式是選擇性的。根據使用者的選擇清單 C 檔案 參閱建構函式。

  • pError
    要接收作業失敗狀態的現有檔案例外狀況物件的指標。

  • pTM
    為 CAtlTransactionManager 物件的指標。

傳回值

如果不是零,開啟成功,則為 0。才會傳回 0, pError 參數是有意義的。

備註

兩個函式會開啟的失敗是一般的檔案,必須有一個條件的「安全性」方法。

CFile 建構函式就會擲回發生錯誤狀況時的例外狀況, 開啟 會傳回錯誤條件的 。不過開啟 仍然可以初始化 CFileException 物件描述錯誤。如果您不提供 pError 參數,或者,如果您傳遞的 pErrorNULL開啟 會傳回 並不會擲回 CFileException。如果您將指標傳遞給現有的 CFileException開啟 遇到錯誤,函式是描述該錯誤的資訊會填滿它。在兩種情況下都不會 開啟 擲回例外狀況。

下表說明 開啟的可能結果。

pError

遇到的錯誤?

傳回值

CFileException 內容

NULL

TRUE

N/A

CFileException的 ptr

TRUE

不會變更。

NULL

FALSE

N/A

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