OpenFileEx function

The OpenFileEx function opens an existing file with the specified name and access mode. Parameters are passed through the stack. The function automatically aligns the stack to 4 bytes.

Parameters (stack): 1. Pointer to the file name. 2. Access mode (READ_ONLY, WRITE_ONLY, READ_WRITE).

Return value: On success (CF=0) AX contains the file handle; 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 OpenFileEx function to open a file with a given access mode through the stack.

title Author: Evgeny Sergeevich Dovgopolov

.286C
.model small
.stack 100h

data segment public
    fName    db "test.txt", 0
    oSuccess db "File '%s' was opened successfully!\0"
    oError   db "An error occurred while opening '%s'. Error code: %d\0"
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 stack
        pushs   ds:[fName]         ; 1st: Push the address of variable fName onto the stack
        call    OpenFileEx         ; Call procedure OpenFileEx(fName, READ_WRITE) := AX and CF

        jnc     @NoOpenFileError   ; If CF=0, jump to label @NoOpenFileError

        push    ax                 ; 3rd: Push ax (error code) onto the stack
        pushs   ds:[fName]         ; 2nd: Push the address of variable fName onto the stack
        leaax   ds:[oError]        ; 1st: Load the address of format string oError into register ds:ax
        call    PrintFormatString  ; Call procedure PrintFormatString(ax:oError, fName, ax)
        add     sp, 4              ; Align the stack
        jmp     @Done              ; Perform an unconditional jump to label @Done

    @NoOpenFileError:
        pushs   ds:[fName]         ; 2nd: Push the address of variable fName onto the stack
        leaax   ds:[oSuccess]      ; 1st: Load the address of format string oSuccess into register ds:ax
        call    PrintFormatString  ; Call procedure PrintFormatString(ax:oSuccess, fName)
        add     sp, 2              ; Align the stack

    @Done:
        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

File 'test.txt' was opened successfully!

Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".