Cake
Cake

Reputation: 21

Writting to txt file in assembly

I am currently working on a project and I need to write numbers to a file. Here is what I've tried so far:

    keyHolder dw ?  
    filename db 'drawlog.txt',0
    filehandle dw ?
    ErrorMsg db 'Error', 13, 10,'$'

proc OpenFile
    mov ah, 3Dh
    mov al, 2
    mov dx, offset filename
    int 21h
    jc openerror
    mov [filehandle], ax
    ret
    openerror:
        mov dx, offset ErrorMsg
        mov ah, 9h
        int 21h
        ret
endp OpenFile

proc closeFile
    mov ah,3Eh
    mov bx,[filehandle]
    int 21h
    ret
endp closeFile

proc writeKeyToFile
    mov ah, 40h
    mov bx,[filehandle]
    mov cx, 1
    mov dx, offset keyHolder
    int 21h
    mov cx,1
    mov ah, 40h
    mov dl, 13
    int 21h
    mov cx,1
    mov ah,40h
    mov dl, 10
    int 21h
    ret
endp writeKeyToFile

The code is sort of working, but there are two things I would like to ask. First, after the write happens the file includes what should have been written and other weird symbols. Second, how can I go down a line when I want to (when writing to the file)?

Upvotes: 0

Views: 987

Answers (2)

AhmadWabbi
AhmadWabbi

Reputation: 2197

keyHolder is not initialized in your code. In order to pass to a new line in the file, declare this variable:

    newline db '\r\n'

Then write it to the file after you write keyHolder. So, the writeKeyToFile function becomes:

proc writeKeyToFile
    mov ah, 40h
    mov bx,[filehandle]
    mov cx, 16
    mov dx, offset keyHolder
    int 21h
    mov ah, 40h
    mov bx,[filehandle]
    mov cx, 2
    mov dx, offset newline
    int 21h
ret

Upvotes: 0

davmac
davmac

Reputation: 20631

after the write happen the file include what should have been written and other weird symbols

You are specifying that 16 bytes should be written (mov cx, 16 - I'm assuming this is DOS, though you don't mention). The address that you specify is only a 2-byte variable. The following 14 bytes presumably contain values that weren't meant to be written to the file.

If keyHolder actually represents a string, don't declare it as a "word" (dw) - it is a sequence of bytes. (Can you even be sure that 2 bytes is enough to represent the number that you are trying to write?)

the second thing is how can I go down a line when I want to(when writing to the file)

Write a Carriage return + Line feed sequence (CRLF; byte value 13 followed by 10).

Upvotes: 1

Related Questions