Search code examples
assemblydosx86-16temporary-files

Assembly 8086 - Using int21h function 5Ah to create a randomly named file


As the title implies, I want to use this function in order to generate a random, unique file name.

My code:

.model tiny
.code

ORG 100H

HOST:

MOV AH, 5Ah
XOR CX, CX
MOV DX, OFFSET HI
int 21h;

MOV BX, DX

mov ax,4c00h
    int 21h
    
mov ah,9
mov dx, OFFSET BX
int 21h
HI DW '\'

END HOST



END

Here is the documentation for the function ->

Thing is, I don't understand what should be put in DX. Path to the folder where the file should be created? Shouldn't it be created by default in the current directory? If not, how can I do that? Tried it with '/' as seen above. Documentation says something about a path ending with 'backslash' + 13 bytes to receive generated filename, but I honestly have no idea what that's supposed to mean. What should be added to the code so that the function will work?


Solution

  • The DOS.CreateUniquelyNamedFile function 5Ah creates a file with a guaranteed unique name in the specified directory. Even though your documentation speaks about a path ending with 'backslash' + 13 bytes, DOS creates just an 8 character file name like "BEAAAGDB" (no extension). 'backslash' + 9 bytes would be enough. Of course, if you want to play it safe then just allocate all 13 bytes.

    To create in a particular directory use e.g. db '\DOS\TEMP\', 9 dup (0).
    To create in the current directory use db '.\', 9 dup (0).
    To create in the parent directory use db '..\', 9 dup (0).
    To create in the root directory use db '\', 9 dup (0) or db 10 dup (0).

    .model tiny
    .code
    
    ORG 100h
    
    HOST:
          mov dx, offset TFile
          xor cx, cx            ; Attribute NORMAL
          mov ah, 5Ah           ; DOS.CreateUniquelyNamedFile
          int 21h               ; -> AX CF
    
          ; Because we exit immediately, there's no need to check the CF for failure
          ; nor do we need to 'close' the file (Terminate does that for us)
    
          mov ax, 4C00h         ; DOS.Terminate
          int 21h
    
    TFile db '.\', 0
        ; db 12 dup(?)     ; implicit at the end of a .COM file
    
    END HOST
    

    TFile is the very last item in this .COM program. So in this case there's no need to use more than the one zero byte as the terminator for the implicit-length C string that DOS will read from this buffer.

    .COM programs can already use space beyond the end of the file as uninitialized buffer space, so the actual path buffer extends into that.