Day 19
Reading Files
Note that when we read files in assembly language that we tell DOS to retreive so many
bytes from the file and we aren't just reading line-by-line, although it would be possible (but perhaps
ineffient) to read byte-by-byte.
Opening and Reading a File
Before we can read anything, we need to open it first:
jmp start
filename db 'elmo.txt',0
handle dw 0 ; will be the file handle. the number that DOS assigns to the open file.
buffer db 255 DUP 0 ; make a plain buffer (not a strange input one like before).
start:
mov ah,3Dh ; 3Dh of DOS Services opens a file.
mov al,0 ; 0 - for reading. 1 - for writing. 2 - both
mov dx,offset filename ; make a pointer to the filename
int 21h ; call DOS
mov handle,ax ; Function 3Dh returns the file handle in AX, here we save it for later use.
DOS Service Function number 3Fh reads from a file.
mov ah,3Fh
mov cx,4 ; I will assume ELMO.TXT has atleast 4 bytes in it. CX is how many bytes to read.
mov dx,offset buffer ; DOS Functions like DX having pointers for some reason.
mov bx,handle ; BX needs the file handle.
int 21h ; call DOS
Here we will put a $ after 4 bytes in the buffer and print the data read:
mov dx,offset buffer
add dx,ax ; Function 3Fh returns the actual amount of bytes read in AX (should be 4 if
; nothing went wrong.
mov bx,dx
mov byte [bx],'$' ; byte pointer so we don't mess with the whole word (a word is 16bits).
Print!!:
mov dx,offset buffer ; put the pointer back in DX.
mov ah,9
int 21h ; call DOS Function 9 (Print String).
mov ah,4Ch
int 21h ; Function 4Ch (Exit Program)
It looks like a lot like that, but don't forget that you can make your own subroutines and CALL them.
This Day In Review
Tomorrow, we get input and then write it to a file!
Have fun!,
- Mike H a.k.a GbaGuy
Intro - Day 20
Patater GBAGuy Mirror
Contact