FREEFILE
- 来源: https://www.freebasic.net/wiki/wikka.php?wakka=KeyPgFreefile
- 最后更新: 2021-01-10
返回可用的文件号
语法
declare function Freefile ( ) as long用法
result = Freefile返回值
下一个可用的文件号(若有),否则返回零(0)。
说明
返回下一个空闲文件号,有效值为 1 到 255,若已有255个文件打开则返回 0。此值是 Open 文件的必需参数。Freefile 在无法追踪已用文件号的复杂程序中非常有用。
请务必在不再需要文件时关闭它们,否则会造成文件号泄漏,程序运行时255个文件号耗尽后将无法再打开任何文件。
Freefile 始终返回最小的空闲文件号。Freefile 返回的文件号在该文件号被 Open 之前,或在有更小的文件号被 Close 之前不会改变:
因此,为确保相同的文件号不会被先在其他地方返回并打开,明智的做法是在对应的
Open之前立即使用Freefile。如果存在与其他线程发生冲突的可能,这个不中断的"
Freefile...Open"序列必须额外被视为临界区代码,因此必须加以保护,例如通过互斥锁(mutex锁定)。
示例
start GeSHi
vb
' Create a string and fill it.
Dim buffer As String, 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 Binary As #f
' Place our string inside the file, using file number "f".
Put #f, , buffer
' Close the file.
Close #f
' End the program. (Check the file "file.ext" upon running to see the output.)
Endend GeSHi
使用多个 Freefile 语句时,Freefile 应紧接在 Open 语句前使用:
start GeSHi
vb
Dim As Long fr, fs
' The CORRECT way:
fr = FreeFile
Open "File1" For Input As #fr
fs = FreeFile
Open "File2" For Input As #fsend GeSHi
而不是:
start GeSHi
vb
Dim As Long fr, fs
' The WRONG way:
fr = FreeFile
fs = FreeFile '' fs has taken the same file number as fr
Open "file1" For Input As #fr
Open "file2" For Input As #fs '' error: file number already openedend GeSHi
平台差异
- 在 Windows 上,动态链接库中使用的文件号与主程序中相同文件号不同。文件号不能在DLL和可执行文件之间传递或返回后使用。
- 除了 FreeBASIC 每个程序同时打开最多255个文件的限制外,还有操作系统对总打开文件数量的限制,但通常不会触及它,除了DOS,其中限制可能低至15个文件。
与 QB 的差异
- 无
另请参阅
OpenPut (File I/O)Get (File I/O)FileAttr
返回 目录