Platform SDK: Files and I/O

LockFile

The LockFile function locks a region in an open file. Locking a region prevents other processes from accessing the region.

To specify additional options, use the LockFileEx function.

BOOL LockFile(
  HANDLE hFile,                   // handle to file
  DWORD dwFileOffsetLow,          // low-order word of offset
  DWORD dwFileOffsetHigh,         // high-order word of offset
  DWORD nNumberOfBytesToLockLow,  // low-order word of length
  DWORD nNumberOfBytesToLockHigh  // high-order word of length
);

Parameters

hFile
[in] Handle to the file with a region to be locked. The file handle must have been created with GENERIC_READ or GENERIC_WRITE access to the file (or both).
dwFileOffsetLow
[in] Specifies the low-order word of the starting byte offset in the file where the lock should begin.
dwFileOffsetHigh
[in] Specifies the high-order word of the starting byte offset in the file where the lock should begin.

Windows 95/98: dwFileOffsetHigh must be 0, the sign extension of the value of dwFileOffsetLow. Any other value will be rejected.

nNumberOfBytesToLockLow
[in] Specifies the low-order word of the length of the byte range to be locked.
nNumberOfBytesToLockHigh
[in] Specifies the high-order word of the length of the byte range to be locked.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

Locking a region of a file gives the locking process exclusive access to the specified region. File locks are not inherited by processes created by the locking process.

Locking a region of a file denies all other processes both read and write access to the specified region. Locking a region that goes beyond the current end-of-file position is not an error.

Locks may not overlap an existing locked region of the file.

If LockFile cannot lock a region of a file, it returns zero immediately. It does not block. To issue a file lock request that will block until the lock is acquired, use LockFileEx without LOCKFILE_FAIL_IMMEDIATELY.

The UnlockFile function unlocks a file region locked by LockFile.

Requirements

  Windows NT/2000: Requires Windows NT 3.1 or later.
  Windows 95/98: Requires Windows 95 or later.
  Header: Declared in Winbase.h; include Windows.h.
  Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CreateFile, LockFileEx, UnlockFile