Opening Files

HomeOverviewHow Do I

In MFC, the most common way to open a file is a two-stage process.

To open a file

  1. Create the file object without specifying a path or permission flags.

    You usually create a file object by declaring a CFile variable on the stack frame.

  2. Call the Open member function for the file object, supplying a path and permission flags.

    The return value for Open will be nonzero if the file was opened successfully or 0 if the specified file could not be opened. The Open member function is prototyped as follows:

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

    The open flags specify which permissions, such as read-only, you want for the file. The possible flag values are defined as enumerated constants within the CFile class, so they are qualified with “CFile::,” as in CFile::modeRead. Use the CFile::modeCreate flag if you want to create the file.

The following example shows how to create a new file with read/write permission (replacing any previous file with the same path):

char* pszFileName = "c:\\test\\myfile.dat";
CFile myFile;
CFileException fileException;

if ( !myFile.Open( pszFileName, CFile::modeCreate |   
          CFile::modeReadWrite ), &fileException )
{
    TRACE( "Can't open file %s, error = %u\n",
       pszFileName, fileException.m_cause );
}

Note   This example creates and opens a file. If there are problems, the Open call can return a CFileException object in its last parameter, as shown here. The TRACE macro prints both the file name and a code indicating the reason for failure. You can call the AfxThrowFileException function if you require more detailed error reporting.