The CloseHandle function
The CloseHandle function closes the file handle.
Parameters: AX: file handle.
Return value: On success (CF=0) the handle is closed; on error (CF=1) AX contains the error code.
Flag state: The function affects all flags.
Program source code
An example program for the Intel 8086 assembler demonstrating the use of the CloseHandle function to close a file handle.
title .model small .stack 100h data segment public fName db "test.txt", 0 fBuffer db 255 dup(0) rError db "An error occurred while reading from the file '%s'. Error code: %d\0" fHandle dw ? data ends code segment public ; Start of the code segment assume ds:data, cs:code include Handyfar.inc ; Include the file with functions main proc ; Start of the main procedure call SetDataSegment ; Call the SetDataSegment procedure mov bl, READ_WRITE ; 2nd: Set the read-write attribute in the bl register lea ax, ds:[fName] ; 1st: Load the address of the fName string into the ds:ax register call OpenFile ; Call the OpenFile procedure (ds:ax, READ_WRITE) := AX and CF mov fHandle, ax ; Save the file handle in the fHandle variable mov cx, 0FFh ; 3rd: Copy the maximum number of bytes to read into the cx register mov bx, fHandle ; 2nd: Copy the fHandle file handle into the bx register lea ax, ds:[fBuffer] ; 1st: Load the address of the fBuffer buffer into the ds:ax register call ReadFile ; Call the ReadFile procedure (ax:fBuffer, bx:fHandle, cx:0FFh) jnc NoReadFileError ; If CF=0, jump to the NoReadFileError label push ax ; 3rd: Save the ax register value (error code) on the stack lea ax, ds:[fName] ; Load the address of the variable fName into the ds:ax register push ax ; 2nd: save the ax register value on the stack lea ax, ds:[rError] ; 1st: Load the address of the rError format string into the ds:ax register call PrintFormatString ; Call the PrintFormatString procedure (ax:rError, fName, ax) add sp, 4 ; Align the stack jmp Done ; Perform an unconditional jump to the Done label NoReadFileError: mov ax, fHandle ; Copy the fHandle file handle into the ax register call CloseHandle ; Call the CloseHandle procedure (ax:fHandle) lea ax, ds:[fBuffer] ; Load the address of the fBuffer buffer into the ds:ax register call WriteString ; Call the WriteString procedure (ax:fBuffer) Done: xor al, al ; Clear the al register call ExitProcess ; Call the ExitProcess procedure main endp ; End of the main procedure code ends ; End of the code segment end main ; End of file. The main procedure is the entry point
This text is from the file!
Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".