RANDOM - QB64 Wiki

RANDOM

From QB64 Wiki

Revision as of 05:47, 4 September 2011 by Clippy (Talk | contribs)
(diff) ← Older revision | Current revision (diff) | Newer revision → (diff)
Jump to: navigation, search

RANDOM is used in an OPEN statement to read(GET) from or write(PUT) to a file.


Syntax:

OPEN Filename$ FOR RANDOM AS #1 [LEN = recordlength%]


  • RANDOM is the Default mode if no mode is given in the OPEN statement.
  • It creates the file if the legal file name given does NOT exist.
  • As a RANDOM file, it can read or write any record using GET and/or PUT statements.
  • Recordlength% is determined by getting the LEN of a TYPE variable or a FIELD statement.
  • If no record length is used in the OPEN statement, the default record size is 128 bytes except for the last record.
  • A record length cannot exceed 32767 or an error will occur!
  • To determine the number of records in a file the records% = LOF \ recordlength%.
  • A serial communication port can also be opened for RANDOM in an OPEN COM statement.


Example: Function that finds a RANDOM file's record number for a string value such as a phone number.

TYPE customer age AS INTEGER phone AS STRING * 10 END TYPE DIM SHARED cust AS customer, recLEN recLEN = LEN(cust) 'get the length of the record type PRINT "RecLEN:"; recLEN OPEN "randfile.rec" FOR RANDOM AS #1 LEN = recLEN FOR i = 1 TO 4 READ cust.age, cust.phone PUT #1, , cust NEXT CLOSE #1 RP = RecordPos("randfile.rec", "2223456789") 'returns 0 if record not found! PRINT RP IF RP THEN OPEN "randfile.rec" FOR RANDOM AS #2 LEN = recLEN GET #2, RP, cust CLOSE #2 PRINT cust.age, cust.phone END IF END DATA 59,2223456789,62,4122776477,32,3335551212,49,1234567890 FUNCTION RecordPos (file$, search$) f = FREEFILE OPEN file$ FOR INPUT AS #f FL = LOF(f) dat$ = INPUT$(FL, f) CLOSE f recpos = INSTR(dat$, search$) IF recpos THEN RecordPos = recpos \ recLEN + 1 ELSE RecordPos = 0 END FUNCTION

Note: Random files can store records holding various variable types using a TYPE definition or a FIELD statement.


See also:



Navigation:
Go to Keyword Reference - Alphabetical
Go to Keyword Reference - By usage
Go to Main WIKI Page