Writing to a file in assembler

Marek M. picture Marek M. · Apr 9, 2015 · Viewed 18.1k times · Source

I'm tasked with creating a program that would write some string to a file. So far, I came up with this:

org     100h

mov     dx, text
mov     bx, filename
mov     cx, 5
mov     ah, 40h
int     21h

mov     ax, 4c00h
int     21h

text db "Adam$"
filename db "name.txt",0

but it doesn't do anything. I'm using nasm and dosbox.

Answer

You have to create the file first (or open it if it already exists), then write the string, and finally close the file. Next code is MASM and made with EMU8086, I post it because it may help you to understand how to do it, interrupts are the same, as well as parameters, so the algorithm :

.stack 100h
.data

text db "Adam$"
filename db "name.txt",0
handler dw ?

.code          
;INITIALIZE DATA SEGMENT.
  mov  ax,@data
  mov  ds,ax

;CREATE FILE.
  mov  ah, 3ch
  mov  cx, 0
  mov  dx, offset filename
  int  21h  

;PRESERVE FILE HANDLER RETURNED.
  mov  handler, ax

;WRITE STRING.
  mov  ah, 40h
  mov  bx, handler
  mov  cx, 5  ;STRING LENGTH.
  mov  dx, offset text
  int  21h

;CLOSE FILE (OR DATA WILL BE LOST).
  mov  ah, 3eh
  mov  bx, handler
  int  21h      

;FINISH THE PROGRAM.
  mov  ax,4c00h
  int  21h