WriteFileEx function

The WriteFileEx function writes data to an open file by its handle. The parameters are passed through the stack. The function automatically aligns the stack to 4 bytes.

Parameters (stack): 1. Pointer to the data. 2. File handle.

Return value: On success (CF=0) AX contains the number of bytes written; 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 WriteFileEx function to write data to an open file by its handle.

title Author: Evgeny Sergeevich Dovgopolov

.286C
.model small
.stack 100h

data segment public
    fName    db "test.txt", 0
    fBuffer  db "Hello, I am learning assembly language!\0"
    wSuccess db "The data was successfully written to the file!\0"
    wError   db "An error occurred while writing to '%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

        push    ax                 ; 2nd: Push the file handle onto the stack
        pushs   ds:[fBuffer]       ; 1st: Push the address of variable fBuffer onto the stack
        call    WriteFileEx        ; Call procedure WriteFileEx(fBuffer, ax) := AX and CF

        jnc     @NoWriteFileError  ; If CF=0, jump to the @NoWriteFileError label

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

    @NoWriteFileError:
        pushs   ds:[wSuccess]      ; Push the address of variable wSuccess onto the stack
        call    WriteStringEx      ; Call procedure WriteStringEx(wSuccess)

    @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

The data was successfully written to the file!

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