The WriteFile function
The WriteFile function writes data to a file using the file descriptor.
Parameters: AX: pointer to the data; BX: file descriptor.
Return value: On success (CF=0) AX contains the number of bytes successfully written; 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 WriteFile function to write data to a file.
title .model small .stack 100h data segment public fName db "test.txt", 0 fBuffer db "Hello, I am learning the assembly language!\0" wSuccess db "The data was successfully written to the file!\0" wError db "An error occurred while writing to the file '%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 and write attribute in the bl register lea ax, ds:[fName] ; 1st: Load the address of the fName string into the ds:ax register call OpenFile ; Call the OpenFile procedure (ds:ax, READ_WRITE) := AX and CF mov bx, ax ; 2nd: Copy the file descriptor (ax) into the bx register lea ax, ds:[fBuffer] ; 1st: Load the address of the fBuffer buffer into the ds:ax register call WriteFile ; Call the WriteFile procedure (ax:fBuffer, bx) jnc NoWriteFileError ; If CF=0, jump to the NoWriteFileError label push ax ; 3rd: Save the ax register value (the 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:[wError] ; 1st: Load the address of the wError format string into the ds:ax register call PrintFormatString ; Call the PrintFormatString procedure (ax:wError, fName, ax) add sp, 4 ; Align the stack jmp Done ; Jump unconditionally to the Done label NoWriteFileError: lea ax, ds:[wSuccess] ; Load the address of the wSuccess buffer into the ds:ax register call WriteString ; Call the WriteString procedure (ax:wSuccess) 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 data was successfully written to the file!
Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".