CLOSE Statement

Syntax

Syntax: CLOSE #n
Source: pb_cg_emit_close (pb_codegen.c:6115)

Description

Closes the file associated with file number #n by calling CloseHandle on the stored Win32 file handle. After closing, the handle slot is zeroed out so the file number can be reused by a subsequent OPEN statement. Calling CLOSE on an already-closed file number is safe; the handle is tested for NULL before the CloseHandle call and the operation becomes a no-op.

All file handles opened by a program are automatically closed when the process terminates, but explicit CLOSE is recommended to flush buffers and release system resources promptly.

Parameters

ParameterDescription
nThe integer file number to close (1 to 255). Must match a previously opened file number.

Example

' Open a file, write to it, then close it
OPEN "output.txt" FOR OUTPUT AS #1
PRINT #1, "Hello World"
PRINT #1, "Line two"
CLOSE #1

' Close is safe even if the file was never opened
CLOSE #2       ' no-op if #2 is not open

' Reuse a file number after closing
OPEN "data1.txt" FOR INPUT AS #3
' ... read data ...
CLOSE #3
OPEN "data2.txt" FOR INPUT AS #3   ' same number, new file

Generated Assembly

mov    rcx, [rbp - handle_offset]        ; load stored file handle
test   rcx, rcx                           ; check if handle is NULL
je     __pb_close_skip                    ; already closed, skip
call   [__imp_CloseHandle]                ; CloseHandle(hFile)
xor    eax, eax
mov    [rbp - handle_offset], rax         ; zero out the stored handle
__pb_close_skip:                          ; fall-through, nothing to do

Imported WinAPI Functions

FunctionDLLPurpose
CloseHandlekernel32.dllClose an open object handle, releasing associated kernel resources

Notes