The CreateFile
function creates or opens a file, device, pipe, communications resource, or mail slot.
HANDLE CreateFileW(
LPCWSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
);
Parameter | Description |
---|---|
lpFileName | Pointer to a null-terminated string that specifies the name of the file or device to be created or opened. |
dwDesiredAccess | Access right flags: GENERIC_READ , GENERIC_WRITE , GENERIC_EXECUTE , or GENERIC_ALL . |
dwShareMode | File sharing mode flags: FILE_SHARE_READ , FILE_SHARE_WRITE , FILE_SHARE_DELETE , or 0. |
lpSecurityAttributes | Optional pointer to a SECURITY_ATTRIBUTES structure. Can be NULL . |
dwCreationDisposition | Action to take on files that exist or do not exist. Typical values: CREATE_NEW , CREATE_ALWAYS , OPEN_EXISTING , OPEN_ALWAYS , TRUNCATE_EXISTING . |
dwFlagsAndAttributes | File attributes and flags. Common values: FILE_ATTRIBUTE_NORMAL , FILE_FLAG_OVERLAPPED , FILE_FLAG_SEQUENTIAL_SCAN , etc. |
hTemplateFile | Handle to a template file with the desired attributes. Usually NULL . |
If the function succeeds, the return value is an open handle to the specified file, device, or resource. If the function fails, the return value is INVALID_HANDLE_VALUE
. To get extended error information, call GetLastError
.
#include <windows.h>
#include <stdio.h>
int wmain(int argc, wchar_t *argv[])
{
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, Windows API!\\n";
DWORD written;
WriteFile(hFile, text, (DWORD)(wcslen(text) * sizeof(wchar_t)), &written, NULL);
CloseHandle(hFile);
wprintf(L"File created and written successfully.\\n");
return 0;
}
CreateFileW
for wide-character support. The ANSI version CreateFileA
is also available but discouraged for new development.