The CreateFile function
The CreateFile function creates a file with the specified name and attributes.
Parameters: AX: pointer to the string with the file name; BX: file creation attributes (READ_ONLY, HIDDEN, SYSTEM, etc.).
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 CreateFile function to create a new file.
title .model small .stack 100h data segment public fName db "test.txt", 0 cSuccess db "The file was created successfully!\0" cError db "An error occurred while creating '%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 bx, READ_ONLY ; 2nd: Set the read-only attribute in the bx register lea ax, ds:[fName] ; 1st: Load the address of the fName string into the ds:ax register call CreateFile ; Call the CreateFile procedure (ds:ax, READ_ONLY) := AX and CF jnc NoCreateFileError ; If CF=0, jump to the NoCreateFileError label 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:[cError] ; 1st: Load the address of the cError format string into the ds:ax register call PrintFormatString ; Call the PrintFormatString procedure (ax:cError, fName, ax) add sp, 4 ; Align the stack jmp Done ; Perform an unconditional jump to the Done label NoCreateFileError: lea ax, ds:[cSuccess] ; Load the address of the variable cSuccess into the ds:ax register call WriteString ; Call the WriteString procedure (ax:cSuccess) 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 created successfully!
Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".