Creating and Opening Files

You can use the CreateFile function to create a new file or open an existing file. You must specify the filename, preferred access, share mode, creation instructions, and attributes.

In the following example, CreateFile opens an existing file for reading.

HANDLE hFile; 
 
hFile = CreateFile("MYFILE.TXT",           // open MYFILE.TXT 
                GENERIC_READ,              // open for reading 
                FILE_SHARE_READ,           // share for reading 
                NULL,                      // no security 
                OPEN_EXISTING,             // existing file only 
                FILE_ATTRIBUTE_NORMAL,     // normal file 
                NULL);                     // no attr. template 
 
if (hFile == INVALID_HANDLE_VALUE) 
{ 
        ErrorHandler("Could not open file.");   // process error 
} 
 

In this example, CreateFile succeeds only if a file named MYFILE.TXT already exists in the current directory. An application should check the return value of CreateFile before attempting to use the handle to access the file. If an error occurs, the application should use the GetLastError function to get extended error information and respond accordingly.

A file must be closed before it can be deleted. The following lines close and delete the MYFILE.TXT file.

CloseHandle(hFile); 
DeleteFile("MYFILE.TXT"); 
 

In the following example, CreateFile creates a new file and opens it for writing.

HANDLE hFile; 
 
hFile = CreateFile("MYFILE.TXT",           // create MYFILE.TXT 
             GENERIC_WRITE,                // open for writing 
             0,                            // do not share 
             NULL,                         // no security 
             CREATE_ALWAYS,                // overwrite existing 
             FILE_ATTRIBUTE_NORMAL |       // normal file 
             FILE_FLAG_OVERLAPPED,         // asynchronous I/O 
             NULL);                        // no attr. template 

if (hFile == INVALID_HANDLE_VALUE) 
{ 
    ErrorHandler("Could not open file.");  // process error 
} 
 

In addition to the standard attributes (read only, hidden, system, and so on), you can also specify security attributes by including a pointer to a SECURITY_ATTRIBUTES structure as the fourth parameter. However, the underlying file system must support security for these attributes for them to have any effect. For more information about security attributes, see Access Control.