Lock
 
Requests a lock on a file range

Syntax

Lock #filenum, record
Lock #filenum, start To end

Parameters

filenum
The file number used to Open the file.
record
The record (Random files) to lock.
start
The first byte position (Binary files) to lock from.
end
The last byte position (Binary files) to lock to.

Description

Lock requests a lock on a file range, usually to allow safe writing to it. The first position and final position are inclusive. A single position locks one byte in a Binary file or one record in a Random file. A start to end range locks every byte or record in that range. If the requested range is already locked incompatibly, the request returns a file I/O error immediately.

After modifying the data, issue Unlock with the same range. Locking behavior depends on the target operating system. On Unix-like systems, file locks are advisory and process-associated, so cooperating programs must use compatible locks. Separate handles in the same process do not conflict with each other, and closing any handle for a file releases all POSIX record locks that process holds on it. A conflict or native lock failure sets a file I/O error. Invalid file numbers or ranges set an illegal function call error.

Targets without a native byte-range locking implementation report a file I/O error instead of claiming that a lock was acquired.

Example

'' e.g. locking a file, reading 100 bytes, and unlocking it. 
'' To run, make sure there exists a file called 'file.ext' 
'' in the current directory that is at least 100 bytes.

Dim array(1 To 100) As Integer
Dim f As Integer, i As Integer
f = FreeFile
Open "file.ext" For Binary As #f
Lock #f, 1 To 100
For i = 1 To 100
    Get #f, i, array(i)
Next
Unlock #f, 1 To 100
Close #f


Differences from QB

  • A single position or explicit range is required; the entire file cannot be locked implicitly

See also