INightmare's Blog

(x86 Assembly) DOS File Input and Output

(This tutorial was originally written in 2004 and featured in http://asm.inightmare.org/)

This tutorial covers basic file Input and Output in DOS.

The first thing you can do is create a file:

mov ah, 3Ch ; DOS create file
mov cx, 0 ; attribute
mov dx, filename ; filename in ASCIIZ
int 21h

filename db "smth.txt",0

Well that’s pretty simple. Carry flag is set if error has occured. Now if we have file, we of course want to open it:

mov ah, 0x3Dh
mov al, oattr ; open attribute: 0 - read-only, 1 - write-only, 2 -read&write
mov dx, filename ; ASCIIZ filename to open
int 21h

If file exists, it’s handle is returned in AX, ff file doesn’t exist Carry Flag is set. Now we can read from our file:

mov ah, 0x3F
mov bx, handle ; handle we get when opening a file
mov cx, num ; number of bytes to read
mov dx, data_ptr ; were to put read data
int 21h

If read is successful AX contains number of bytes red, if reading failed as always Carry Flag is set. Now writing:

mov ah, 0x40
mov bx, handle ; file handle
mov cx, size ; num of bytes to write
mov dx, data ; data to write
int 21h

If write is successful CF is clear and AX contains number of bytes written, else CF is set and AX contains an error code. After we did what we want, we can close the file:

mov ah, 0x3E
mov bx, handle ; file handle
int 21h

And deleting files for the dessert:

mov ah, 41h
mov dx, filename ; ASCIIZ filename to delete
int 21h

filename db "smth.txt", 0

Those are the basics you need to know. Good luck!

Example code