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

ParameterDescription
lpFileNameThe name of the file or device to be created or opened.
dwDesiredAccessThe requested access to the file or device.
dwShareModeThe requested sharing mode of the file or device.
lpSecurityAttributesA pointer to a SECURITY_ATTRIBUTES structure.
dwCreationDispositionAn action to take on files that exist, and which action to take when files do not exist.
dwFlagsAndAttributesThe file or device attributes and flags.
hTemplateFileA 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;
}

See also