Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

I/O in Assembly

Status
Not open for further replies.

TheNewbieOnASM

Programmer
Jul 27, 2003
4
US
I trying to write a program in Assembly that open a file and then write to it and then close it after writing to it, but I have no idea where to start. Can you give me some example code in Assembley?



( ? )
o
o
(O_O)
 
It is easiest to use the DOS interrupts. I have written the program below to demonstrate a simple file handling program:
Code:
assume cs:code,ds:data

data segment

filename   db 'test.txt',0
filehandle dw  ?
buffer     db 0A0h ; Max input size
           db 0A1h dup (0)
err_open   db 'Error Opening !$'
msg_open   db 'Open successful',0dh,0ah,'$'
msg_text   db 'Enter some text> $'

data ends

code segment
  org 100h

write_prog:
  jmp start

start:
  ; update DS...
  mov ax,data
  mov ds,ax

  ; open file
  mov ah,3dh
  mov al,00010001b ; open for write
  lea dx,filename
  int 21h
  jnc openOK

  ; error msg
  mov ah,09h
  lea dx,err_open
  int 21h
  jmp terminate

openOK:
  mov filehandle,ax ; save for later
  mov ah,09h
  lea dx,msg_open
  int 21h
  lea dx,msg_text
  int 21h

; buffered key input...
  lea dx,buffer
  mov ah,0ah
  int 21h

; write to file
  mov ah,40h
  mov bx,filehandle
  lea dx,buffer
  inc dx
  mov di,dx
  inc dx
  sub ch,ch
  mov cl,[di]     ; no. bytes to write
  int 21h

; close file
  mov ah,3eh
  mov bx,filehandle
  int 21h

terminate:
  mov ax,4c00h
  int 21h

code ends


end write_prog
Most of that should be straight-foreward. But here are a few noteworthy points:
1) The program looks for the file 'test.txt' in the current directory. If it doesn't find the file, an error msg is dumped and program ends.
2) The file is opened at the first byte. Any previous data in the file (if any) will be overwritten. It should be easy to adjust the program for appending.

For more information on the DOS interrupts, try looking up on Ralf Browns List (you can get to one from Any problems, post again. :)
 
When I run the codes that you posted it, the compiler pop up with a message that said unknown byte 6Eh. Can you tell me why it said that and why did it happend?

Thank you, for the example code :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top