12.4. Getting a free file number

[<<<] [>>>]

At certain situation you do not know a number which is sure available to be associated with a file. In that case you can use the function FreeFile() to get a file number usable in the next open statement.

The following code demonstrates the usage of the function FREEFILE:

fn = FREEFILE
Open "myfile.txt" for input as fn

The first line of the code stores a number in the variable fn, which can be used in the next line as a file number. You can print out the actual value, store it in one or more variables.

To be absolutely safe you can also check if there is any available file number. If there is no available file number then the function FREEFILE returns undef.

fn = FREEFILE
if IsDefined(fn) then

open "myfile.txt" for input as fn else

' do whatever you have to do

' when you can not open the file end if

There is another way to automatically get the first free file number in an OPEN statement.

In case the file number is specified using a single variable initialized to zero the interpreter will find automatically the first available file number and will put this value into the variable. This way you can also write:

fn = 0
ON ERROR GOTO ERROR$FILE$NOT$OPENED
open "myfile.txt" for input as fn

' do whatever you want with the file

STOP

ERROR$FILE$NOT$OPENED: ' do whatever you have to do ' when you can not open the file


[<<<] [>>>]