WriteFileExD function

The WriteFileExD function opens a file by itself, writes data to it and closes it. The parameters are passed through the stack. The function automatically aligns the stack to 4 bytes.

Parameters (stack): 1. Pointer to the file name. 2. Pointer to the data to write.

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 WriteFileExD function to open a file, write data to it and close it automatically.

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

        pushs   ds:[fBuffer]       ; 2nd: Push the address of variable fBuffer onto the stack
        pushs   ds:[fName]         ; 1st: Push the address of variable fName onto the stack
        call    WriteFileExD       ; Call procedure WriteFileExD(fName, fBuffer) := 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)".