Microsoft Docs

File I/O Windows API

CreateFile function

The CreateFile function creates or opens a file, device, pipe, communications resource, or mail slot.

Syntax

HANDLE CreateFileW(
    LPCWSTR               lpFileName,
    DWORD                 dwDesiredAccess,
    DWORD                 dwShareMode,
    LPSECURITY_ATTRIBUTES lpSecurityAttributes,
    DWORD                 dwCreationDisposition,
    DWORD                 dwFlagsAndAttributes,
    HANDLE                hTemplateFile
);

Parameters

ParameterDescription
lpFileNamePointer to a null-terminated string that specifies the name of the file or device to be created or opened.
dwDesiredAccessAccess right flags: GENERIC_READ, GENERIC_WRITE, GENERIC_EXECUTE, or GENERIC_ALL.
dwShareModeFile sharing mode flags: FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_SHARE_DELETE, or 0.
lpSecurityAttributesOptional pointer to a SECURITY_ATTRIBUTES structure. Can be NULL.
dwCreationDispositionAction to take on files that exist or do not exist. Typical values: CREATE_NEW, CREATE_ALWAYS, OPEN_EXISTING, OPEN_ALWAYS, TRUNCATE_EXISTING.
dwFlagsAndAttributesFile attributes and flags. Common values: FILE_ATTRIBUTE_NORMAL, FILE_FLAG_OVERLAPPED, FILE_FLAG_SEQUENTIAL_SCAN, etc.
hTemplateFileHandle to a template file with the desired attributes. Usually NULL.

Return value

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.

Example

#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;
}
Note: Use the Unicode version CreateFileW for wide-character support. The ANSI version CreateFileA is also available but discouraged for new development.

Copy sample to clipboard

Related functions