Main - About - Tutorials - Articles - Files - Opcodes - Links  

Untitled Document

DOS: File Input/Output

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 ofcourse 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 succesful 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 succesful CF is clear and AX contains num 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

If you're evil and you want to delete files, here's smth for ya:

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. Wait for more tutorials. See ya, and good luck with coding.

Example code.

Copyright InternetNightmare © - 2004-2009