Matrix File I/O

Matrix File I/O

Top  Previous  Next

 

QMBasic has two styles of file i/o that may be freely mixed within an application. Using READ and WRITE to transfer data using dynamic arrays is simpler and usually faster for programs that do little processing of the data or work with records that have few fields. For programs that perform a significant amount of processing of the data in records that have many fields, it may be worth the cost of breaking the fields into separate elements of a dimensioned matrix using MATREAD and MATWRITE.

 

These statement have the same locking variants as their dynamic array counterparts. They also share an almost identical syntax where the prefix MAT is used to select the matrix version of the operation and the variable representing the database record must be a dimensioned array. For example, the dynamic array read:

READ var FROM filevar, id

becomes

MATREAD array FROM filevar, id

 

 

The MATREAD statement places each field of the record into a separate element of the array, keeping values and subvalues together as these are instances of the same data item.

 

For example, if a record has three fields, the second of which is multivalued:

AFMB1VMB2FMC

using MATREAD to read this into a three element (plus the zero element) matrix would result in:

 

0


1

A

2

B1VMB2

3

C

 

The MATWRITE operation joins together each element of the matrix, inserting field marks between them and writes this to the file.

 

 

If the matrix has more elements than there are fields in the record, the excess elements are set to null strings:

 

0


1

A

2

B1VMB2

3

C

4


5


 

The INMAT() function can be used after a MATREAD to determine how many elements of the matrix were used. The MATWRITE operation ignores all trailing empty fields so that above situation would not write two empty fields at the end of the record.

 

 

If the matrix has fewer elements than there are fields in the record, the zero element is used to store the excess data. Consider the a record with five fields and a matrix with three elements:

 

0

DFME

1

A

2

B1VMB2

3

C

 

The MATWRITE operation adds the contents of the zero element to the record formed from the remaining elements of the matrix, reconstructing the correctly formed data. The zero element thus acts as an "overflow bucket" allowing programs that did not expect to find the excess data to function correctly.

 

Pick style matrices do not have a zero element. In this case, the excess data is stored in the final element of the matrix:

 

1

A

2

B1VMB2

3

CFMDFME

 

This is likely to cause the program to malfunction if it updates element 3 where it expected only to find the third field of the database record. To avoid this, Pick style programmers usually ensure that the matrix has at least one more element than they expect it to need, effectively moving the "overflow bucket" to the end of the matrix.