The OpenFile function
The OpenFile function opens access to a file with the specified name and attributes.
Parameters: AX: pointer to the string with the file name; BL: file open attributes (READ_ONLY, WRITE_ONLY, READ_WRITE).
Return value: On success (CF=0) AX contains the file handle; on error (CF=1) AX contains the error code.
Flag state: The function affects all flags.
Program source code
An example program for the Intel 8086 assembler demonstrating the use of the OpenFile function to open an existing file.
title .model small .stack 100h data segment public fName db "test.txt", 0 oSuccess db "The file was opened successfully!\0" oError db "An error occurred while opening '%s'. Error code: %d\0" data ends code segment public ; Start of the code segment assume ds:data, cs:code include Handyfar.inc ; Include the file with functions main proc ; Start of the main procedure call SetDataSegment ; Call the SetDataSegment procedure mov bl, READ_WRITE ; 2nd: Set the read-write attribute in the bl register lea ax, ds:[fName] ; 1st: Load the address of the string fName into the ds:ax register call OpenFile ; Call the OpenFile procedure (ds:ax, READ_WRITE) := AX and CF jnc NoOpenFileError ; If CF=0, jump to the label NoOpenFileError push ax ; 3rd: Save the ax register value (error code) on the stack lea ax, ds:[fName] ; Load the address of the variable fName into the ds:ax register push ax ; 2nd: save the ax register value on the stack lea ax, ds:[oError] ; 1st: Load the address of the format string oError into the ds:ax register call PrintFormatString ; Call the PrintFormatString procedure (ax:oError, fName, ax) add sp, 4 ; Align the stack jmp Done ; Perform an unconditional jump to the label Done NoOpenFileError: lea ax, ds:[oSuccess] ; Load the address of the variable oSuccess into the ds:ax register call WriteString ; Call the WriteString procedure (ax:oSuccess) Done: xor al, al ; Clear the al register call ExitProcess ; Call the ExitProcess procedure main endp ; End of the main procedure code ends ; End of the code segment end main ; End of file. The main procedure is the entry point
The file was opened successfully!
Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".