Put Statement |
No
Put [#]filenumber, [recnumber], varname
filenumber
Use: Required
Data Type: Integer
Any valid file number.
recnumber
Use: Optional
Data Type: Variant (Long)
Record or byte number to begin the write operation.
varname
Use: Required
The name of the variable containing the data to be written to the file.
Writes data from a program variable to a disk file.
If filenumber is opened in random access mode, recnumber refers to the record number; if the file is opened in binary access mode, recnumber refers to a byte number.
Both bytes and records in a file are numbered from 1 upward.
If recnumber is omitted, the next byte or record to be written is placed at the position immediately after the position pointed to by the last Get or Put statement, or by the last Seek function. To omit recnumber, you must use the delimiting commas, as the following statement shows:
Put #1,,myVar
If you have opened the file in random mode, it's important to ensure that the record length specified in the Len clause of the Open statement matches the actual length of the data being written. If the length of the data being written is less than that specified by the Len clause, the space up to the end of the record is padded with the current contents of the file buffer—whatever that may be. If, on the other hand, the actual data length is more than that specified, an error occurs.
Certain data types complicate determining the actual data length of a record. These data types need a secondary data element called a descriptor to inform VB of either their underlying data type or their physical length. The following table details the descriptors used in VB:
Variable Data Type | Descriptor |
---|---|
Variable-length string | 2 bytes containing length of string |
Variant (numeric) | 2 bytes identifying VarType |
Variant (string) | 2 bytes containing length + 2 bytes identifying vartype |
Dynamic array | 2 + (8 × number of dimensions) |
Any other data types | No descriptor |
User-defined type | Each element treated the same as the individual data type |
If the file was opened in random access mode, you can use the Put statement to write a variant array to disk.
The Put statement can't write objects to disk.
If you open the file in binary mode, the Len clause has no effect. When you use Put to write data to the disk, the data is written contiguously, and no padding is placed between records.
When you write arrays to disk using the Put statement with a file opened in binary mode, only arrays contained within a user-defined type have the array descriptor added; all other arrays are written to disk without the descriptor. Individual array elements, however, may have descriptors, depending on their data types.
Similarly, variable-length strings written to a file opened in binary mode are written without the two-byte descriptor.
Because of the structured format of data written with the Put statement, it's customary to read the data back from the file using the Get statement.