ReadFileExD function

The ReadFileExD function opens a file by itself, reads data into a buffer and closes it. Parameters are passed through the stack. The function automatically aligns the stack to 6 bytes.

Parameters (stack): 1. Pointer to the file name. 2. Pointer to the buffer. 3. Number of bytes to read.

Return value: On success (CF=0) AX contains the number of bytes read; 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 ReadFileExD function to open, read and close a file automatically.

title Author: Evgeny Sergeevich Dovgopolov

.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"
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    0FFh               ; 3rd: Push the number of bytes to read onto the stack
        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    ReadFileExD        ; Call procedure ReadFileExD(fName, fBuffer, 255) := AX and CF

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

        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:[rError]        ; 1st: Load the address of format string rError into register ds:ax
        call    PrintFormatString  ; Call procedure PrintFormatString(ax:rError, fName, ax)
        add     sp, 4              ; Align the stack
        jmp     @Done              ; Perform an unconditional jump to label @Done

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

    @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

This text is from the file!

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