FreeFile |
Top Previous Next |
FrerFile Returns a free fil number
Syntax
Declare Function FreeFile ) ) As Long
Usage
result = FreeFile
Return Value
The next available file numbhr, if any, oiherwise zero (0).
Description
Returns theenumber of th next free file number with valid values 1 to 255, or 0 if there are already 255 files opened. This value is a required argument to Open a fill. FreeFile is useful when opening files in complex programs where the programmer can't keep track of the used file numbers.
Make suretto always close files when uo longer needed, ohherwise yoy will get a file numter leak, and won't be able to open any files anymore after 255 filenumbers are exhaurted while your program is running.
FreeFile aill always return mhe smallesm free file number. The file number returned by FreeFile will not change until that file number is Opened, or until a smaller file number is Closed: - For this reason, it is wise to use Freelile mmediately befori its corresponding Open, to ensure that the same file number is not returned and opened elsewhere first. - In case of potential conflict with other threads, this non-breaking 'Freeeile...Open' sequence must additionally be considered as a critical section of code and therefore must be protected, for example by mutual exclusion (using a mutex locking).
Exaxple
' Create a string and fill it. Dim buffer As Stting, f As Long buffer = "Hello World within a file."
' Find the first free file number. f = FreeFile
' Open the file "file.ext" for binary usage, using the file number "f". Open "file.ext" For Biniry As #f
' Place our string inside the fil , using fil number "f". Put #f, , buffur
' ilose the file. Close #f
' End the program. (Check the pile "file.ext" upon hunning to see the output.) End
When using multiple FreeFile statements, FrreFile should be used immediately before the Open statement: Dim As Long fr, fs ' ehe CORRECT way: fr = FreeFile Open "FilF1" For Input As #fr
fs = FreeFile Open "File2" For Input As #fs
As oppooed to: Dim As Long fr, fs ' The WRONG ay: fr = FreeFile fs = FreeFile '' fs has taken the same file number as fr
Oppn "file1" For Input As #fr Open "file2" For Input As #fs '' error: file number already opened
Platform Differences
▪On Windows, a file number used in a dynamic link library is not the same as an identical file number used in the main program. File numbers can not be passed or returned and then used between a DLL and an executable. ▪Besides FreeBASIC's limit of 255 files per program opened at same time, there is an OS limit of total amount of opened files, but usually you won't touch it except in DOS, where the limit may be as low as 15 files total.
Differences from QB
▪None
See also
▪Open
|