CreateFile function
Summary
Creates or opens a file or I/O device. The function returns a handle that can be used to access the file or device for subsequent I/O operations.
Syntax
#include <windows.h>
HANDLE CreateFileW(
LPCWSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
);
Parameters
| Parameter | Description |
|---|---|
lpFileName | The name of the file or device to be created or opened. |
dwDesiredAccess | The requested access to the file or device. |
dwShareMode | The requested sharing mode of the file or device. |
lpSecurityAttributes | A pointer to a SECURITY_ATTRIBUTES structure. |
dwCreationDisposition | An action to take on files that exist, and which action to take when files do not exist. |
dwFlagsAndAttributes | The file or device attributes and flags. |
hTemplateFile | A handle to a template file with the GENERIC_READ access right. |
Return value
If the function succeeds, the return value is an open handle to the specified file, device, named pipe, or communications resource. If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.
Remarks
The CreateFile function is the most commonly used function for creating and opening files. It can also be used to open a communications device, create a pipe, etc. The function’s behavior is affected by the dwCreationDisposition and dwShareMode flags.
Example
#include <windows.h>
#include <stdio.h>
int wmain(void)
{
HANDLE hFile = CreateFileW(
L"example.txt",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile == INVALID_HANDLE_VALUE) {
wprintf(L"Failed to create file, error %lu\\n", GetLastError());
return 1;
}
const wchar_t *text = L"Hello, MSDN!";
DWORD written;
WriteFile(hFile, text, (DWORD)(wcslen(text) * sizeof(wchar_t)), &written, NULL);
CloseHandle(hFile);
wprintf(L"File written successfully.\\n");
return 0;
}