Data can easily be read from a data file using analogous statements as outputting to a file. i.e. there are four steps to do this:
These four commands are listed below:
ChDrive "P:" ChDir "\My_Directory" Open "EXAMPLE.DAT" For Input As #1 Input #1, X Close #1
Here the first two lines set the drive and the directory where the input file is sitting. i.e. the ChDrive "P:" sets the drive to be the P: drive, and the ChDir "My_Directory" sets the directory within that drive to be My_Directory. Note that you must put the drive and directory name inside quotation marks (i.e. the ChDrive and ChDir must have a string following it). Note also that these ChDrive and ChDir lines are both optional. If you don't have them, then the default directory is used (see above).
The file is opened (or prepared to be input from) with the Open command.
Then the INPUT command is used to input the variable X from the file.
Finally the file is closed.
You will note that the lines of code are exactly analogous to the code which was used to do the outputting (see Sec.).
A very common problem is to read in an numbers from a data file of unknown length. The best method of doing this is illustrated below:
ChDrive "P:" ChDir "\Test_dir" Open "EXAMPLE.DAT" For Input As #7 While Not EOF(7) Input #7, A,B Wend Close #7
In the above EOF(7) stands for "end-of-file 7". So the above While loop will continue to loop so long as the program has not reached the end of the file. Note also, that in the case above, EXAMPLE.DAT must contain two columns of data.
CHECKPOINT: Write a program which reads in two numbers A and B from the data file SAMPLE.DAT and then outputs their average value to the file AVERAGE.DAT.
Here it is for you! (Note, you'll have to have a file called SAMPLE.DAT with two numbers in it on the same line for this programme to work.)
There are three steps to inputting to a data file: (i) Open the file; (ii) Input from the file; (iii) Close the file. Optionally, you may wish to specify which directory the file will be in before any of these steps.
The While loop (as shown above) is very useful to read in data from a file of unknown length.