Games often need to store data on a file, for example, high scores or level progress. The file access commands in AppGameKit Studio provide the ability to deal with tasks such as this. In this particular example commands are used that show the opening and reading of data from a file.
The process involved is as follows:
The command to open a file for writing is called OpenToWrite. It either takes one or two parameters dependant on usage. The first option is to have the command return an ID number for later usage, when taking this option the command only requires one parameter - the filename. If you want to specify an ID number then the command takes two parameters - the ID and the filename.
This line of code shows the first option:
fileID = OpenToRead ( "myfile.txt" )
An ID for the file is returned to the variable fileID, the first parameter "myFile.txt" tells AppGameKit Studio that we want to open this particular file.
The alternative approach is to specify an ID number manually, instead of it being assigned in the return value:
OpenToRead ( 1, "myfile.txt" )
For the purpose of our example an ID number will be specified manually.
There are three possible data types that can be read from a file:
Our test file will contain the following data:
To read an integer from file call the ReadInteger command. This command takes one parameter - the ID of the file. This line of code reads an integer from the file, in this case 10:
value = ReadInteger ( 1 )
To read a string from a file call the ReadString command. This command takes one parameter - the ID of the file. This line of code read the string "hello" from file 1:
string$ = ReadString ( 1 )
To read a float from a file call the ReadFloat command. This command takes one parameter - the ID of the file. This line of code reads the value 1.23 from file 1:
value# = ReadFloat ( 1 )
Once all data has been read from a file that file must be closed using the command CloseFile. This commands only parameter is the ID of the file. To close file 1:
CloseFile ( 1 )
Our final program will read from a file containing this data:
Here's the code:
OpenToRead ( 1, "myfile.txt" )
a = ReadInteger ( 1 ) b# = ReadFloat ( 1 ) c$ = ReadString ( 1 )
CloseFile ( 1 )
As you can see from the above code, opening a file and reading data from it is a simple process. The important point to note is that you must read data in the correct order. Our file had an integer, a float and then a string, so we had to read it in that order.