Controls access by other processes to all or part of a file opened using the Open statement.
Lock [#]filenumber[, recordrange]
. . .
Unlock [#]filenumber[, recordrange]
The Lock and Unlock statement syntax has these parts:
Part |
Description |
filenumber |
Any valid file number. |
recordrange |
The range of records to lock or unlock. |
The recordrange argument settings are:
recnumber | [start] To end
Setting |
Description |
recnumber |
Record number (Random mode files) or byte number (Binary mode files) at which locking or unlocking begins. |
start |
Number of the first record or byte to lock or unlock. |
end |
Number of the last record or byte to lock or unlock. |
The Lock and Unlock statements are used in environments where several processes might need access to the same file.
Lock and Unlock statements are always used in pairs. The arguments to Lock and Unlock must match exactly.
The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you specify just one record, then only that record is locked or unlocked. If you specify a range of records and omit a starting record (start), all records from the first record to the end of the range (end) are locked or unlocked. Using Lock without recnumber locks the entire file; using Unlock without recnumber unlocks the entire file.
If the file has been opened for sequential input or output, Lock and Unlock affect the entire file, regardless of the range specified by start and end.
Caution Be sure to remove all locks with an Unlock statement before closing a file or quitting your program. Failure to remove locks produces unpredictable results.
Open Statement.
This example illustrates the use of the Lock and Unlock statements. While a record is being modified, access by other processes to the record is denied. This example assumes that TESTFILE is a file containing five records of the user-defined type Record.
Type Record ' Define user-defined type. ID As Integer Name As String * 20TypeMyRecord As Record ' Declare variable. ' Open sample file for random access."TESTFILE" For Random Shared As #1 Len = Len(MyRecord)= 4 ' Define record number.#1, RecordNumber ' Lock record.#1, RecordNumber, MyRecord ' Read record..ID = 234 ' Modify record..Name = "John Smith"#1, RecordNumber, MyRecord ' Write modified record.#1, RecordNumber ' Unlock current record.#1 ' Close file.