ReadFileEx function

The ReadFileEx function reads data from an open file by handle. Parameters are passed through the stack. The function automatically aligns the stack to 6 bytes.

Parameters (stack): 1. Pointer to the buffer. 2. File handle. 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 ReadFileEx function to read data from an open file into a buffer.

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"
    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 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
        mov     fHandle, ax        ; Save the file handle in variable fHandle

        push    0FFh               ; 3rd: Push the number of bytes to read onto the stack
        push    fHandle            ; 2nd: Push the file handle fHandle onto the stack
        pushs   ds:[fBuffer]       ; 1st: Push the address of variable fName onto the stack
        call    ReadFileEx         ; Call procedure ReadFileEx(fBuffer, fHandle, 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)".