CloseHandleEx function
The CloseHandleEx function closes a file handle. The handle is passed through the stack. The function automatically aligns the stack to 2 bytes.
Parameters (stack): 1. 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
Intel 8086 assembly program example demonstrating the use of the CloseHandleEx function to close a file handle passed through the stack.
title .286C .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 '%s'. Error code: %d\0" fHandle dw ? data ends code segment public assume ds:data, cs:code include Handyfar.inc ; Include the file with functions include Handymac.inc ; Include the file with macros main proc call SetDataSegment ; Call the SetDataSegment procedure push READ_WRITE ; 2nd: Push the READ_WRITE attribute onto the top of the stack pushs ds:[fName] ; 1st: Push the address of the fName variable onto the top of the stack call OpenFileEx ; Call the OpenFileEx(fName, READ_WRITE) procedure := AX and CF mov fHandle, ax ; Save the file handle in the fHandle variable push 0FFh ; 3rd: Push the number of bytes to read onto the top of the stack push fHandle ; 2nd: Push the file handle fHandle onto the top of the stack pushs ds:[fBuffer] ; 1st: Push the address of the fName variable onto the top of the stack call ReadFileEx ; Call the ReadFileEx(fBuffer, fHandle, 255) procedure jnc @NoReadFileError ; If CF=0, jump to the label @NoReadFileError push ax ; 3rd: Push ax onto the top of the stack (error code) pushs ds:[fName] ; 2nd: Push the address of the fName variable onto the top of the stack leaax ds:[rError] ; 1st: Load the address of the rError format string into the ds:ax register call PrintFormatString ; Call the PrintFormatString(ax:rError, fName, ax) procedure add sp, 4 ; Align the stack jmp @Done ; Perform an unconditional jump to the label @Done @NoReadFileError: pushs ds:[fBuffer] ; Push the address of the fBuffer variable onto the top of the stack call WriteStringEx ; Call the WriteStringEx(fBuffer) procedure @Done: push fHandle ; Push the file handle fHandle onto the top of the stack call CloseHandleEx ; Call the CloseHandleEx(fHandle) procedure push 0 ; Push the byte return code onto the top of the stack call ExitProcessEx ; Call the ExitProcessEx(0) procedure main endp code ends end main
This text is from the file!
Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".