Microsoft Learn

CreateFileW

Opens or creates a file or I/O device (such as a COM port).

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

This function is typically used to perform general I/O operations on a file. For specific operations, consider using specialized functions such as CreateFileMapping, CreateNamedPipe, or CreateToolhelp32Snapshot.

Parameters

Parameter Description
lpFileName

The name of the file or device to be created or opened.

For block devices, the name can be a physical disk (\\\.\PhysicalDrive0), or a logical disk (\\\.\C:).

For specific device types, see the documentation for that device.

dwDesiredAccess

The requested access to the file or device. The most common values are:

  • GENERIC_READ: 0x80000000
  • GENERIC_WRITE: 0x40000000
  • GENERIC_EXECUTE: 0x20000000
  • GENERIC_ALL: 0x10000000

This parameter can be any combination of the access rights.

dwShareMode

A bitmask that specifies the sharing mode of the object. This parameter determines whether subsequent open-requests for the object will be permitted. The possible values are:

  • 0: Requests for read, write, or delete on the object will fail until the calling process has closed the handle to the object.
  • FILE_SHARE_READ: Subsequent requests to open the object for reading are allowed.
  • FILE_SHARE_WRITE: Subsequent requests to open the object for writing are allowed.
  • FILE_SHARE_DELETE: Subsequent requests to open the object for deleting are allowed.

This parameter can be any combination of the previous values.

lpSecurityAttributes

A pointer to a SECURITY_ATTRIBUTES structure that contains the security descriptor for the file or device. If this parameter is NULL, the file or device is created with a default security descriptor.

dwCreationDisposition

An action that specifies what to do if the file or device already exists or does not exist.

This parameter can be one of the following values:

  • CREATE_NEW: Creates a new file. If the file exists, the operation fails.
  • CREATE_ALWAYS: Creates a new file. If the file exists, the operation overwrites the file.
  • OPEN_EXISTING: Opens the file. If the file does not exist, the operation fails.
  • OPEN_ALWAYS: Opens the file. If the file does not exist, the function creates a new file.
  • TRUNCATE_EXISTING: Opens the file and truncates it so that it has zero length. If the file does not exist, the operation fails.
dwFlagsAndAttributes

A bitmask that specifies attributes and flags for the file or device. This parameter can include file attributes, such as FILE_ATTRIBUTE_NORMAL, or flags that control how the file is to be created or opened, such as FILE_FLAG_OVERLAPPED.

For a complete list of attributes and flags, see the MSDN documentation for CreateFile.

hTemplateFile

A handle to a template file with the GENERIC_READ access right. The template file provides extended attributes for the file being created.

If this parameter is NULL, the new file has the same extended attributes as the specified file. For more information, see CopyFile.

Return value

If the function succeeds, the return value is a new, open handle to the specified file or device. The type of the object indicated by the return value, the access specified by dwDesiredAccess, and the flags specified by dwFlagsAndAttributes.

If the function fails, the return value is INVALID_HANDLE_VALUE. To get error information, call GetLastError.

Remarks

The CreateFileW function is the most versatile function for opening files and devices. It can be used to open any file or device that can be accessed with a handle.

Note

For Unicode support, it is recommended to use CreateFileW. The CreateFileA function is provided for compatibility with ANSI applications.

When opening a file, CreateFileW can return a handle to an existing file or create a new file, depending on the value of dwCreationDisposition.

When opening a device, such as a serial port, CreateFileW can be used to set various device parameters by specifying flags in dwFlagsAndAttributes.

File Attributes and Flags

The dwFlagsAndAttributes parameter can be used to specify various file attributes and flags. Some common flags include:

  • FILE_ATTRIBUTE_NORMAL: Normal file. Applications use this attribute for files that do not have any other attributes set. This attribute is valid only on Windows.
  • FILE_FLAG_BACKUP_SEMANTICS: This flag indicates that the file is being opened for backup or restore. The system ensures that the application can access the file even if the file contains data that cannot otherwise be accessed.
  • FILE_FLAG_DELETE_ON_CLOSE: Indicates that a file or directory is to be deleted when the last handle to it is closed.
  • FILE_FLAG_OVERLAPPED: The file is being opened for asynchronous I/O.

Sharing Mode

The dwShareMode parameter is crucial for concurrent access to files. Setting it to 0 effectively locks the file for the calling process until the handle is closed. Carefully choose the share mode to prevent data corruption in multi-threaded or multi-process scenarios.

Examples

Here's a simple example of how to create or open a file for writing:


#include <windows.h>
#include <iostream>

int main() {
    HANDLE hFile = CreateFileW(
        L"my_document.txt",          // File name
        GENERIC_WRITE,               // Desired access: write only
        0,                           // Share mode: no sharing
        NULL,                        // Security attributes: default
        CREATE_ALWAYS,               // Creation disposition: create or overwrite
        FILE_ATTRIBUTE_NORMAL,       // Flags and attributes: normal
        NULL                         // Template file: none
    );

    if (hFile == INVALID_HANDLE_VALUE) {
        std::cerr << "Failed to open or create file. Error: " << GetLastError() << std::endl;
        return 1;
    }

    std::cout << "File opened/created successfully. Handle: " << hFile << std::endl;

    // Write some data to the file (example)
    const char* data = "Hello from CreateFileW!\r\n";
    DWORD bytesWritten;
    if (!WriteFile(hFile, data, strlen(data), &bytesWritten, NULL)) {
        std::cerr << "Failed to write to file. Error: " << GetLastError() << std::endl;
    } else {
        std::cout << "Successfully wrote " << bytesWritten << " bytes." << std::endl;
    }

    CloseHandle(hFile);
    std::cout << "File handle closed." << std::endl;

    return 0;
}
                

Requirements

Value
Minimum supported client Windows 2000 Professional
Minimum supported server Windows 2000 Server
Header fileapi.h (include Windows.h)
Library Kernel32.lib
DLL Kernel32.dll
Unicode and ANSI versions CreateFileW (Unicode) and CreateFileA (ANSI) are available.