| description | Learn more about: Opening Files | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| title | Opening Files | |||||||||||||
| ms.date | 11/04/2016 | |||||||||||||
| helpviewer_keywords |
|
|||||||||||||
| ms.assetid | a991b8ec-b04a-4766-b47e-7485b5dd0b01 |
In MFC, the most common way to open a file is a two-stage process.
-
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.
-
Call the Open member function for the file object, supplying a path and permission flags.
The return value for
Openwill be nonzero if the file was opened successfully or 0 if the specified file could not be opened. TheOpenmember 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
CFileclass, so they are qualified with "CFile::" as inCFile::modeRead. Use theCFile::modeCreateflag 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):
[!code-cppNVC_MFCFiles#1]
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.