FREEFILE function

Purpose | Return the next available PowerBASIC file number.
Syntax | x% = FREEFILE

Remarks

FREEFILE returns an Integer value in the range 1 to 32767, which dictates the next available file number that may be used to OPEN a file or device. Using FREEFILE, your program can open files and devices without the need to keep track of which file numbers are already in use.

FREEFILE is thread-safe, returning a new file number with each invocation. This means that two or more consecutive calls to FREEFILE will return different file numbers regardless of whether they were used to open a file or not. This behavior differs from previous versions of PowerBASIC, where FREEFILE returned the same file number consistently until the file number was actually used to open a file or device.

FREEFILE is vastly superior to using hard-coded file numbers because it eliminates the possibility of a file number being used more than once in a module at any given moment.

A file number returned by FREEFILE can be used with the COMM OPEN, TCP OPEN and UDP OPEN statements, as well as standard file I/O OPEN and OPEN HANDLE statements.

Use FILENAME$ to return the name of the open file that corresponds to a given file number.

Restrictions

FREEFILE returns file numbers within a predictable and convenient range of values. PowerBASIC file numbers are also specific (private) to the PowerBASIC module in which they are used to OPEN a file or device. This means that a file number in use in one module will have no definition or meaning if passed to another module or API function.

However, it can sometimes be necessary for a different module or even an API function to access a file that is already open. In this case, it is necessary to use the FILEATTR function to obtain the operating system file handle, and this value can be passed to other modules or API functions. These modules would use the OPEN HANDLE statement to gain access into the already-open file.

See also | COMM OPEN, FILEATTR, FILENAME$, OPEN, TCP OPEN, UDP OPEN
Example | x%= FREEFILE OPEN MyFileName$ FOR OUTPUT AS #x%