Win32 API Reference

Microsoft Docs

Win32 API Functions

This section provides detailed reference information for the Win32 API functions, which are the core building blocks for developing Windows applications.

CreateFile

The CreateFile function creates or opens a file or I/O device. It returns a handle that can be used to access the file or device.

Syntax

HANDLE CreateFile( _In_ LPCTSTR lpFileName, _In_ DWORD dwDesiredAccess, _In_ DWORD dwShareMode, _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes, _In_ DWORD dwCreationDisposition, _In_ DWORD dwFlagsAndAttributes, _In_opt_ 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. This can be a combination of GENERIC_READ, GENERIC_WRITE, or other access flags.
dwShareMode Specifies how the file or device should be shared. This can be 0, FILE_SHARE_READ, FILE_SHARE_WRITE, or a combination.
lpSecurityAttributes A pointer to a SECURITY_ATTRIBUTES structure that specifies the security descriptor for the file or device. If this parameter is NULL, the file or device gets a default security descriptor.
dwCreationDisposition Specifies the action to take if the file or device already exists. This can be CREATE_NEW, CREATE_ALWAYS, OPEN_EXISTING, OPEN_ALWAYS, or TRUNCATE_EXISTING.
dwFlagsAndAttributes The file attributes and flags for the file or device. This can include flags like FILE_ATTRIBUTE_NORMAL, FILE_FLAG_RANDOM_ACCESS, etc.
hTemplateFile A handle to a template file with the GENERIC_READ access right. This template file supplies optional template parameters for the file being created.

Return Value

If the function succeeds, the return value is an open handle to the specified file or device. If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.

Remarks

The CreateFile function is a versatile function used for interacting with various file system objects and devices.

  • When opening an existing file, ensure that dwDesiredAccess and dwShareMode are set appropriately to avoid conflicts with other processes.
  • The dwCreationDisposition parameter controls how the function behaves when the specified file name already exists.
  • For devices, the interpretation of some parameters might differ from their use with regular files.
Note: This documentation is for the Win32 API. For modern Windows development, consider using the Windows Runtime (WinRT) API or .NET Framework.