본문 바로가기

C++ in Windows/MFC

CFile, CFileException


MSDN - CFile Members(클릭)

MSDN 예제보기
 //example for CFile::Open
CFile f;
CFileException e;
char* pFileName = "test.dat";
if( !f.Open( pFileName, CFile::modeCreate | CFile::modeWrite, &e ) )
   {
#ifdef _DEBUG
   afxDump << "File could not be opened " << e.m_cause << "\n";
#endif
   }

//A second example for CFile::Open.
//This console program uses CFile to copy binary files.

#include <afx.h>
#include <afxwin.h>
#include <iostream>

using namespace std;

CWinApp theApp;

int main(int argc, char *argv[])
{
   if (!AfxWinInit(GetModuleHandle(NULL), NULL, GetCommandLine(), 0))
   {
      cout << "panic: MFC couldn't initialize!" << endl;
      return 1;
   }

   // constructing these file objects doesn't open them

   CFile sourceFile;
   CFile destFile;

   // see that we have a reasonable number of arguments

   if (argc != 3)
   {
      cout << "usage: " << argv[0];
      cout << "  <dest>" << endl;
      cout << endl;
      return 1;
   }

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

   CFileException ex;

   // open the source file for reading

   if (!sourceFile.Open(argv[1],
      CFile::modeRead | CFile::shareDenyWrite, &ex))
   {
      // complain if an error happened
      // no need to delete the ex object

      TCHAR szError[1024];
      ex.GetErrorMessage(szError, 1024);
      cout << "Couldn't open source file: ";
      cout << szError;
      return 1;
   }
   else
   {
      if (!destFile.Open(argv[2], CFile::modeWrite |
            CFile::shareExclusive | CFile::modeCreate, &ex))
      {
         TCHAR szError[1024];
         ex.GetErrorMessage(szError, 1024);
         cout << "Couldn't open source file: ";
         cout << szError;

         sourceFile.Close();
         return 1;
      }

      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 0;
}

예제를 보다보면 CFileException(클릭)라는 클래스가 나왔다. 이 클래스는 CFile::Open 메소드 실행시 포인터 인수로 넘겨주는데, 예외가 발생될 경우 추적을 쉽게 해주는 클래스이다.

'C++ in Windows > MFC' 카테고리의 다른 글

CString <-> int  (0) 2012.01.12
CTime  (0) 2012.01.11