LockFile Function

Overview

The LockFile function locks a region of a file, blocking the calling process until the operating system grants access to the region.

The LockFileEx function provides more control over the locking operation.

Tip: For robust file locking, especially in concurrent scenarios, consider using LockFileEx with appropriate flags.

Syntax

BOOL LockFile(
                    HANDLE hFile,
                    DWORD dwFileOffsetLow,
                    DWORD dwFileOffsetHigh,
                    DWORD nNumberOfBytesToLockLow,
                    DWORD nNumberOfBytesToLockHigh
                );

This function is defined in fileapi.h.

Parameters

Parameter Description
hFile A handle to the file to be locked. The handle must have been created with the GENERIC_READ or GENERIC_WRITE access right.
dwFileOffsetLow The low-order 32 bits of the byte offset in the file at which to start the lock.
dwFileOffsetHigh The high-order 32 bits of the byte offset in the file at which to start the lock.
nNumberOfBytesToLockLow The low-order 32 bits of the number of bytes to lock.
nNumberOfBytesToLockHigh The high-order 32 bits of the number of bytes to lock. If this parameter is 0 and nNumberOfBytesToLockLow is also 0, the lock extends from the current file offset to the end of the file.

Return Value

TRUE (BOOL): If the function succeeds, the return value is nonzero. Otherwise, the return value is zero. To get extended error information, call GetLastError.

A region can be locked by multiple processes, but the region must be locked by the same process before it can be unlocked.

A region is automatically unlocked when the handle to the file is closed.

Requirements

Attribute 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

See Also