OpenFileEx 函数

OpenFileEx 函数以指定的访问模式打开已存在的文件。参数通过栈传递。函数会自动将栈对齐 4 个字节。

参数(栈): 1. 文件名的指针。2. 访问模式(READ_ONLY、WRITE_ONLY、READ_WRITE)。

返回值: 成功时(CF=0)AX 中包含文件句柄;出错时(CF=1)AX 中包含错误代码。

标志状态: 函数会影响所有标志。

程序源代码

Intel 8086 汇编程序示例,演示使用 OpenFileEx 函数通过栈以指定的访问模式打开文件。

title Author: Dovgopolov Evgeny Sergeevich

.286C
.model small
.stack 100h

data segment public
    fName    db "test.txt", 0
    oSuccess db "File '%s' opened successfully!\0"
    oError   db "Error opening '%s'. Error code: %d\0"
data ends

code segment public
    assume  ds:data, cs:code
    include Handyfar.inc           ; 包含函数文件
    include Handymac.inc           ; 包含宏文件

    main proc
        call    SetDataSegment     ; 调用过程 SetDataSegment

        push    READ_WRITE         ; 第2步:将属性 READ_WRITE 压入栈顶
        pushs   ds:[fName]         ; 第1步:将变量 fName 的地址压入栈顶
        call    OpenFileEx         ; 调用过程 OpenFileEx(fName, READ_WRITE) := AX 和 CF

        jnc     @NoOpenFileError   ; 如果 CF=0,则跳转到标签 @NoOpenFileError

        push    ax                 ; 第3步:将 ax(错误代码)压入栈顶
        pushs   ds:[fName]         ; 第2步:将变量 fName 的地址压入栈顶
        leaax   ds:[oError]        ; 第1步:将格式字符串 oError 的地址装入寄存器 ds:ax
        call    PrintFormatString  ; 调用过程 PrintFormatString(ax:oError, fName, ax)
        add     sp, 4              ; 对齐栈
        jmp     @Done              ; 无条件跳转到标签 @Done

    @NoOpenFileError:
        pushs   ds:[fName]         ; 第2步:将变量 fName 的地址压入栈顶
        leaax   ds:[oSuccess]      ; 第1步:将格式字符串 oSuccess 的地址装入寄存器 ds:ax
        call    PrintFormatString  ; 调用过程 PrintFormatString(ax:oSuccess, fName)
        add     sp, 2              ; 对齐栈

    @Done:
        push    0                  ; 将字节值(返回代码)压入栈顶
        call    ExitProcessEx      ; 调用过程 ExitProcessEx(0)
    main endp

code ends
end main

File 'test.txt' opened successfully!

示例取自教材 "HANDYFAR - MASM (Dovgopolov Evgeny Sergeevich)".