Amiga Basic Tutorial

File Input and Output

Amiga Basic includes some simple file functions to open, read,write and close files. The following statements are commonly used:

OPEN "filename" [FOR INPUT | OUTPUT | APPEND] AS filenumber
OPEN mode, [#] filenumber, filename [,file-buffer-size]
CLOSE [#]filenumber[ , ...]
EOF(filenumber)
INPUT$(x [,[#] filenumber)
INPUT #filenumber, variable-list
WRITE #filenumber, expression-list
PRINT #filenumber, [USING string-expr;] expression-list
GET [#]filenumber,][,recordnumber]
PUT [#]filenumber [,recordnumber]
FIELD [#]filenumber, fieldwidth AS string-variable, ...
LSET string-variable=string-expression
RSET string-variable=string-expression

The filenumber can be an integer from 1 to 255.
The filename can a any valid file name and path e.g. DF0:Myfile.txt, Work:Myfile.txt etc.
The mode for OPEN can be a string: O for output, I for input, R for random i/o access, and A for append. In the first OPEN statement, if the FOR mode part is absent, then it will default to Random i/o access.
The file-buffer-size for open can be a value from 128 bytes to 32767 bytes (by default it is 128 bytes).
The EOF function returns true if it detects the end of the file and no more data can be read.
The Get, Put, Field, Lset and Rset statements can only be used for Random access files.
The fieldwidth for FIELD can be a value upto to the value of buffer-size specified in the OPEN statement.
The variables for LSET and RSET should only be used for use with File i/o and never used with LET or INPUT statements.

Sequential File Input and Output.

For sequential files use the normal INPUT, OUTPUT or APPEND modes for the OPEN statement. The difference between Output and Append is that Output will create a new file if it does not exist and if it does already exist, will overwrite the existing contents. Append will always add new data to the end of the existing file. The following example, will write out 20 numbers to a file, and read them back in and print them to the console.

REM File Example
REM by P Hutchison
  
PRINT "Writing numbers to numbers.dat."
REM Open file for writing
OPEN "numbers.dat" FOR OUTPUT AS 1
FOR n=1 to 20
PRINT #1, n
NEXT n
CLOSE 1

REM Read numbers from a file
PRINT "Reading file numbers.dat."
REM Open existing file for reading
OPEN "numbers.dat" FOR INPUT AS 1
WHILE NOT EOF(1)
INPUT #1, num
PRINT "Number ";num
WEND
CLOSE 1
END   

Random File Input and Output

Here is an example of randomly picking records from a customer database file.

REM Read records from a customer database
OPEN "customers.dat" AS 1 LEN=155
REM customer no, firstname, lastname, address, telephone
FIELD 1,C$ AS 10, 25 AS f$, 25 AS l$, A$ AS 100, T$ AS 20
RECNO = 1
WHILE RECNO>0
INPUT "Record Number? ";RECNO
GET #1, RECNO
PRINT "Customer Number: "; C$
PRINT "First Name: "; F$
PRINT "Last Name: ";L$
PRINT "Address:" ' A$
PRINT "Telephone: "; T$
PRINT " "
WEND
END

Next Page