6

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.

Marek M.
  • 3,799
  • 9
  • 43
  • 93

1 Answers1

11

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           
  • In this line: `mov handler, ax` there's a problem. Nasm tells me "invalid combination of opcode and operands". – Marek M. Apr 09 '15 at 18:44
  • Maybe the name "handler" is a reserved word. Change the variable's name, for example, file_handler. – Jose Manuel Abarca Rodríguez Apr 09 '15 at 18:46
  • I changed the name, but I'm still getting this error. If I comment out only this line, then the program compiles and creates the file (without contents). – Marek M. Apr 09 '15 at 18:48
  • In order to write to the file and close it we require the file handler. When the file is created the handler is returned in AX, let's do this : MOV AX, DI, we are saving the handler in DI. Change all "handler" by DI. – Jose Manuel Abarca Rodríguez Apr 09 '15 at 18:49
  • Yes, I understand that. I commented this line out just to check if it will work without it - not if it will work properly. – Marek M. Apr 09 '15 at 18:50
  • 3
    @SzwornyDziąch in NASM, when reading/writing values from/to a labeled memory location, the label needs to be in brackets. So try `mov [handler], ax` and, further down, `mov bx, [handler]`. Referencing just the name `handler` is the literal address value. The above answer is in MASM, which uses a different syntax. – lurker Apr 09 '15 at 18:52
  • 1
    We can put the file handle into BX just after opening/creating a file. The write function(AH=40h) and also the read function(3Fh) do not destroy the contend of BX. But with terminating the programm with AH=4Ch int 21h all open files will be finally closed too and no data will be lost. – Dirk Wolfgang Glomp Apr 10 '15 at 05:35
  • @Szworny Dziąch works like charm in emu8086 assembler. – Ahtisham Nov 18 '17 at 11:31