Creating Data Files

Most programs need to save data of some sort, so you need to know how to create a file, write data to it and then be able to read it back. This program does just that.

(Right at the start there is a Trap Delete filename$ line. This means delete filename$ and ignore any errors. You need this otherwise the second time the program is run, it will fail because you can't Create a file if it already exists, which it will from the first time you ran the program. The Trap (which means ignore errors) is required because the first time the program is run there won't be any file to delete and so Delete would come up with an error.)

The program creates a data file using Create filename$,A,f1$,f2%. The A is used as a file handle, a sort of pointer to the file if you like. (Use A to Z for file handles.) You can have many fields in this data file and they can be any type of variable. Here I've just used two fields - a string and an integer. Note that you don't need to define them with a Local statement.

You assign values to the fields just like regular variables, except you put the file handle in front of everything. So to set the first field - a string called f1$ - to "String1" we use: A.f1$="String1". After giving the fields values Append is used to write the data (called a record) to the file. More data is assigned to A.f1$ and A.f2% and Append is used again to write the data record to the file. Finally, the file is closed.

To read the data back we use Open instead of Create, otherwise things are pretty much as before. The values are read back into two ordinary variables and printed on the screen. Then we move to the next record with Next and repeat the process. Finally, the file is closed.

PROC DataFiles:
Local filename$(255),a$(255),b%

filename$="c:\TestFile"

Rem Delete it if it exists
Trap Delete filename$

Print "Creating data file...";
Create filename$,A,f1$,f2%
A.f1$="String1"
A.f2%=123
Append
A.f1$="String2"
A.f2%=321
Append
Close
Print "Finished"
Print

Print "Reading data file..."
Open filename$,A,f1$,f2%
a$=A.f1$
b%=A.f2%
Print "Record 1: ";a$,b%
Next     Rem Next record
a$=A.f1$
b%=A.f2%
Print "Record 2: ";a$,b%
Close
Print "Finished"
Print
Print "Press a key..."
Get

ENDP
 

RAW Computing home page

  Psion home page