Reading and writing files tutorial
Back to index


The dos interrupt contains functions which makes it easy to create, open, read, write, close and delete files.
A file should always be closed before the program is terminated.

Create file

Function 3ch creates a file. ds:dx should point to the ASCIIZ filename. cx is is the file attribute.
Here is a lift of the attributes:
Bit Description
0 Read only
1 Hidden
2 System
3 Volume label
4 Always zero
5 Archive bit
6 -
7 -
On return the carry flag will be set if an error occurred. If succesful ax is the file handle.

    mov ah,3ch
    mov cx,00000000b
    lea dx,filename
    int 21h
    jc error
    mov handle,ax

Open file

Function 3dh opens a file. ds:dx points to the ASCIIZ filename. If al is 0 then the file is opened as read only, if al is 1 the file will be opened as write only and if al is 2 the file will be opened as read/write.
On return cf is set if an error occurred. ax is the file handle if succesful.

    mov ax,3d02h
    lea dx,filename
    int 21h
    jc error
    mov handle,ax

Read from file

Function 3fh reads a string from a file. bx is the file handle, cx is the number of bytes you want to read and ds:dx is where to put them.
On return cf is set if an error occourred. ax is equal to the number of bytes read. If ax is different from cx end of file occurred.

    mov ah,3fh
    mov bx,handle
    mov cx,1000
    lea dx,buffer
    int 21h
    jc error

Write to file

Function 40h writes a string to a file. bx is the file handle, cx is the number of bytes to write and ds:dx points to the string you want to write. On return cf is set if an error occurred.

    mov ah,40h
    mov bx,handle
    mov cx,1000
    lea dx,buffer
    int 21h
    jc error

Move file pointer

If the file is bigger than 64kb you need to use function 42h to read the whole file. It moves the file pointer to a new location. cx is the high bits of the new location and dx is the low bits. al is where you want to move the pointer from. 0 is beginning of file, 1 is the current location and 2 is end of file. bx is the file handle. On return cf is set if an error occurred.

    mov ax,4200h
    mov bx,handle
    mov cx,1
    mov dx,1
    int 21h
    jc error

Delete file

Function 41h deletes a file. ds:dx points to the ASCIIZ filename. On return cf is set if an error occurred.

    mov ah,41h
    lea dx,filename
    int 21h
    jc error

Close file

Function 3eh closes a file. bx is the file handle. On return cf is set if an error occurred.

    mov ah,3eh
    mov bx,handle
    int 21h
    jc error

In the sample program filea.com creates a file and fileb.com deletes it.
files.zip (1321 bytes)


Jesper L. Poulsen