; working with files

DATASEG
filename      db  'record.txt',0
filehandle    dw  ?
errormsg      db 'Error',10,13,'$' 
numofbytes    equ 7
oldscore      db  '$$$$$$$$'
fullper       db  8 dup ('$') 

CODESEG

;-----------------------------------------------------------------------------------------------------
proc          createfile 
              mov bx,1                     ; bx=1 means create failed
              mov ah,3Ch
              mov cx,0              
              mov dx, offset filename
              int 21h 
              jc  nosuccess
              mov bx,0
              mov [filehandle],ax    
nosuccess:    ret
endp          createfile
;-----------------------------------------------------------------------------------------------------
proc          openfile                   ; bx=0 open succeeded, bx=1 file does not exist
              mov  bx,0                  ; bx=2  other error with the file
              mov  ah,3Dh
              mov  al,2
              lea  dx,[filename]
              int  21h
              jc   openerror
              mov  [filehandle],ax
              ret
openerror:  
              mov   bx,1
              cmp   ax,2               ; ax==2 File not found
              je    endit
              mov   bx,2               ; Other error than file not found             
endit:        ret
endp          openfile
;-----------------------------------------------------------------------------------------------------
proc          readfile
              mov ah,3Fh
              mov bx,[filehandle]
              mov cx, numofbytes
              mov dx,offset oldscore
              int 21h     
              ret  
endp          readfile 
;-----------------------------------------------------------------------------------------------------
proc          writefile                ; Receives a parameter - how many bytes to write
              push bp
              mov  bp,sp
              mov  ah,40h
              mov  bx,[filehandle]
              mov  cx,[bp+4]           ; length of string to write
              mov  dx, offset fullper
              int  21h
              pop  bp
              ret  2  
endp          writefile 
;-----------------------------------------------------------------------------------------------------
proc          closefile
              mov ah,3Eh
              mov bx,[filehandle]
              int 21h
              ret  
endp          closefile 