CFile::Open
Overloaded. Open is designed for use with the default CFile constructor.
virtual BOOL Open( LPCTSTR lpszFileName, UINT nOpenFlags, CFileException* pError = NULL ); virtual BOOL Open( LPCTSTR lpszFileName, UINT nOpenFlags, CAtlTransactionManager* pTM, CFileException* pError = NULL );
The two functions form a "safe" method for opening a file where a failure is a normal, expected condition.
While the CFile constructor will throw an exception in an error condition, Open will return FALSE for error conditions. Open can still initialize a CFileException object to describe the error, however. If you don't supply the pError parameter, or if you pass NULL for pError, Open will return FALSE and not throw a CFileException. If you pass a pointer to an existing CFileException, and Open encounters an error, the function will fill it with information describing that error. In neither case will Open throw an exception.
The following table describes the possible results of Open.
|
pError |
Error encountered? |
Return value |
CFileException content |
|---|---|---|---|
|
NULL |
No |
TRUE |
n/a |
|
ptr to CFileException |
No |
TRUE |
unchanged |
|
NULL |
Yes |
FALSE |
n/a |
|
ptr to CFileException |
Yes |
FALSE |
initialized to describe error |
//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; }