You can use the CreateFile function to create a new file or open an existing file. You must specify the filename, desired access, share mode, creation instructions, and attributes.
In the following code fragment, 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 */
(LPSECURITY_ATTRIBUTES) NULL, /* no security */
OPEN_EXISTING, /* existing file only */
FILE_ATTRIBUTE_NORMAL, /* normal file */
(HANDLE) NULL); /* no attr template */
if (hFile == INVALID_HANDLE_VALUE) {
ErrorHandler("Could not open file."); /* process err on fail*/
}
In this example, CreateFile will only succeed if a file named “MYFILE.TXT” already exists in the current directory. Other processes can read the file, but not write to it.
An application should check the return value of CreateFile before attempting to use the handle to access the file. If an error occurred, the application should use GetLastError to obtain extended error information and respond accordingly.
An application must close a file before the file can be deleted. The following lines close and delete the file MYFILE.TXT:
CloseHandle(hFile);
DeleteFile("myfile.txt");
In the following code fragment, 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 */
(LPSECURITY_ATTRIBUTES) NULL, /* no security */
CREATE_ALWAYS, /* overwrite existing */
FILE_ATTRIBUTE_NORMAL | /* normal file */
FILE_FLAG_OVERLAPPED, /* asynchronous i/o */
(HANDLE) NULL); /* no attr template */
if (hFile == INVALID_HANDLE_VALUE) {
ErrorHandler("Could not open file."); /* process err on fail*/
}
In addition to the standard attributes (read-only, hidden, system, etc.) you can also specify security attributes by including a pointer to a SECURITY_ATTRIBUTES structure as the fourth parameter. However, the underlying operating system must support security for these attributes to have any effect. For more information about security, see Chapter 9, “Security.”