File Operations in Assembly Language

The following all use the MS-DOS API (int 21) to do these file operations.

(MKDIR) Create Folder

C:\>debug
-a 0100
xxxx:0100 mov ah,39                ;Create folder func.
xxxx:0102 mov dx,010c              ;Points to pathname
xxxx:0105 int 21                   ;Do it
xxxx:0107 mov ax,4c00              ;AH=Exit, AL=Errorlevel
xxxx:010A int 21                   ;Do it
xxxx:010C db "C:\NewFolder1",00    ;Null terminated pathname
xxxx:011A
-n makef.com
-r cx
CX 0000
:001a
-w
Writing 001A bytes.
-q

Remove Folder

C:\>debug
-a 0100
xxxx:0100 mov ah,3a               ;Remove folder func.
xxxx:0102 mov dx,010C             ;points to pathname
xxxx:0105 int 21                  ;Do it
xxxx:0107 mov ax,4c00             ;Exit func., AL=Errorlevel
xxxx:010A int 21                  ;Do it
xxxx:010C db "C:\OldFolder1",00   ;Null terminated pathname
xxxx:011A
-n rmvf.com
-r cx
CX 0000
:001a
-w
Writing 001A bytes.
-q

Create/Truncate File

C:\>debug
-a 0100
xxxx:0100 mov ah,3c     ;Create file func.
xxxx:0102 mov cx,2      ;Archive file attribute
xxxx:0105 mov dx,010f   ;Points to filename
xxxx:0108 int 21        ;Do it
xxxx:010A mov ax,4c00
xxxx:010D int 21
xxxx:010F db "C:\Users\jakash3\newfile1.txt",00
-n mkf.com
-r cx
CX 0000
:002D
-w
Writing 001A bytes.
-q

Note:
File attributes are specified by the hex value of a bit array.

  0   1   2   3   4   5   6   7
+---+---+---+---+---+---+---+---+
| ? | ? | ? | 0 | 0 | ? | 0 | 0 |
+---+---+---+---+---+---+---+---+

0 – Read Only
1 – Hidden
2 – System
3 – Volume label (ignored)
4 – Reserved, must be zero (directory)
5 – Archive
6 – Unused
7 – Unused

A Read-Only Archive file: 10000100
In hex that would be: 84
So 84 would be the value for CX in the 3C function of Int 21.

Open File

C:\>debug
-a 0100
xxxx:0100 jmp 011c
xxxx:0102 db "C:\Users\jakash3\data.txt",00
xxxx:011C mov ah,3d     ;Open file func.
xxxx:011E mov al,40     ;Bit field for read/write access
xxxx:0120 mov dx,0102   ;Points to filename
xxxx:0123 int 21        ;Do it

File access mode bit fields for this function:

  0   1   2   3   4   5   6   7
+---+---+---+---+---+---+---+---+
| ? | ? | ? | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+

000 – Read Only (mov cl,0)
001 – Write Only (mov cl,20)
010 – Read/Write (mov cl,40)

After the interrupt call, AX should contain the file handle if no errors occurred.

Close File

C:\>debug
-a 0100
xxxx:0100 jmp 011c
xxxx:0102 db "C:\Users\jakash3\data.txt",00
xxxx:011C mov ah,3d     ;Open file function
xxxx:011E mov al,40     ;Bit field for read/write access
xxxx:0120 mov dx,0102   ;Points to filename
xxxx:0123 int 21        ;Do it
xxxx:0125 mov bx,ax     ;Move file handle to BX for 3e function -------+
xxxx:0127 mov ax,3e00   ;Close file function <------------------------/
xxxx:012A int 21        ;Do it

Read from file

C:\>debug
xxxx:0100 jmp 012b
xxxx:0102 db "C:\Users\jakash3\ab.txt",00 ;filename to read from
xxxx:011A db 00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,24 ;'$' terminated 10 byte buffer
xxxx:012B mov ah,3d     ;Open file function
xxxx:012D mov al,00     ;Read-Only file access
xxxx:012F mov dx,0102   ;Points to filename
xxxx:0132 int 21        ;Do it
xxxx:0134 mov bx,ax     ;Move retrieved file handle into BX
xxxx:0136 mov ax,3f00   ;Read from file function
xxxx:0139 mov cx,10     ;Read the first 0x10 bytes of file
xxxx:013C mov dx,011a   ;Address of buffer to store bytes read
xxxx:013F int 21        ;Do it
xxxx:0141 mov ax,0900   ;Print string function
xxxx:0144 mov dx,011a   ;Points to '$' terminated string to print
xxxx:0147 int 21        ;Do it
xxxx:0149 mov ax,4c00   ;Exit function (AL=Errorlevel to return)
xxxx:014C int 21        ;Do it
xxxx:014E
-rcx
CX 0000
:004e
-n readfile.com
-w
Writing 0004E bytes
-q

Write to file:

C:\>debug
xxxx:0100 jmp 0101
xxxx:0102 db "C:\Users\jakash3\ab.txt",00
xxxx:011A db "hello world!",00
xxxx:0127 mov ah,3d   ;Open file function
xxxx:0129 mov al,20   ;Write-Only file access
xxxx:012B mov dx,0102 ;Points to filename
xxxx:012E int 21      ;Do it
xxxx:0130 mov bx,ax   ;Move retrieved file handle into BX
xxxx:0132 mov ax,4000 ;Write to File function
xxxx:0135 mov dx,011a ;Points to data to write
xxxx:0138 mov cx,0d   ;Number of bytes to write
xxxx:013A int 21      ;Do it
xxxx:013C mov ax,4c00 ;Exit function
xxxx:013F int 21      ;Do it
xxxx:0140
-r cx
CX 0000
:0040
-n wfile.com
-w
Writing 0040 bytes.
-q

Delete file:

C:\>debug
-a 0100
xxxx:0100 mov ah,40   ;Delete file function
xxxx:0102 mov dx,010c ;Points to filename
xxxx:0105 int 21      ;Do it
xxxx:0107 mov ax,4c00 ;Exit function
xxxx:010A int 21      ;Do it
xxxx:010C db "C:\Users\jakash3\ab.txt",00
xxxx:0124
-r cx
CX 0000
:0024
-n delf.com
-w
Writing 0024 bytes.
-q

29 thoughts on “File Operations in Assembly Language

  1. Thank you so much!!! I have searched all over the web and couldn’t find these functions! BTW only the folder delete/create work with DOS 6.22(but who uses that any more) also works great with FreeDOS.

  2. ca you hel me with this program…it doesnt show errors but it doesnt read the file that is created…. can you help me??? sorry with my english….

    .model small
    .stack
    .code

    start:

    mov ax,@data ; endereço de base do segmento de dados
    mov ds,ax ; é colocado em ds

    mov dx,OFFSET ficheiro ; coloca o endereço do nome do arquivo em dx
    mov al,2 ; modo de acesso – leitura e escrita
    mov ah,3Dh ; função 3Dh – abre um arquivo
    int 21h ; chama serviço do DOS

    mov Handle,ax ; guarda o manipulador do arquivo para mais tarde
    jc ErrorOpening ; desvia se carry flag estiver ligada – erro!

    mov dx,offset Buffer ; endereço do buffer em dx
    mov bx,Handle ; manipulador em bx
    mov cx,100 ; quantidade de bytes a serem lidos
    mov ah,3Fh ; função 3Fh – leitura de arquivo
    int 21h ; chama serviço do DOS

    jc ErrorReading ; desvia se carry flag estiver ligada – erro!

    mov bx,Handle ; coloca manipulador do arquivo em bx
    mov ah,3Eh ; função 3Eh – fechar um arquivo
    int 21h ; chama serviço do DOS

    mov cx,100 ; comprimento da string
    mov si,OFFSET Buffer ; DS:SI – endereço da string
    xor bh,bh ; página de vídeo – 0
    mov ah,0Eh ; função 0Eh – escrever caracter

    NextChar:

    lodsb ; AL = próximo caracter da string
    int 10h ; chama serviço da BIOS
    loop NextChar

    mov ax,4C00h ; termina programa
    int 21h

    ErrorOpening:

    mov dx,offset OpenError ; exibe um erro
    mov ah,09h ; usando a função 09h
    int 21h ; chama serviço do DOS
    mov ax,4C01h ; termina programa com um errorlevel =1
    int 21h

    ErrorReading:
    mov dx,offset ReadError ; exibe um erro
    mov ah,09h ; usando a função 09h
    int 21h ; chama serviço do DOS
    mov ax,4C02h ; termina programa com um errorlevel =2
    int 21h

    .data
    Handle DW ? ; para guardar o manipulador do arquivo
    ficheiro DB “C:\test.txt”,0 ; arquivo a ser aberto
    OpenError DB “Ocorreu um erro ao abrir o ficheiro!$” ; erro
    ReadError DB “Ocorreu um erro ao ler o ficheiro!$” ; erro
    Buffer DB 100 dup (?) ; buffer para armazenar dados

    END start

    • I didn’t look at the entire code but I believe I see a problem on this instruction: “mov Handle,ax”
      where it should be “mov [Handle],ax” or “mov word [Handle],ax”. It’s indirection, we’re copying contents of ax to the memory pointed to by Handle.

  3. @jakash3. can you help us in our object oriented programming language in java and in our tasm? can you leave your email-address so we can reach you? we’re computer science students from phils. :D

  4. welcom to all
    Could we kindly help me? I have one problem in my program in my program as mention below
    I need instruction between output from assembly program to output file that means output from program appear in output file
    please top urgent
    thanks and regard

    • xxxx:0100 mov ah,39 ;Create folder func.
      xxxx:0102 mov dx,010c ;Points to pathname
      xxxx:0105 int 21 ;Do it
      xxxx:0107 mov ax,4c00 ;AH=Exit, AL=Errorlevel
      xxxx:010A int 21 ;Do it
      xxxx:010C db “C:\NewFolder1”,00 ;Null terminated pathname

      Hi,
      in the secondo row, how do you know that db address will be 010C?

      • I don’t. At first I just use a random address. After I finish the last lines of data, I go back and edit the code to put the right address. Use the A command specifying the address of where to edit.

  5. Hi jakash3,
    in your post did you write:
    r cx
    CX 0000
    :004e

    Why did you write 004e value? Is a fixed value or optional value (ie: could you write also 001e value?)?

  6. can someone explain to me how to copy the content of a file to another? something like, copy f1 f2 , and to copy the ontent of the file f1 to f2 and if the f2 dowsn’t exist to creat it or something

    • does anyone know how to find duplicate files on different directories by comparing file names, not necessarily its contents using assembly language? console program using tasm & tlink … i hope someone could help regarding this machine problem ..

  7. .model small
    .stack
    .data
    .code
    apaga:
    db “data.txt”,00
    mov ah,3d ;Open file function
    mov al,40 ;Bit field for read/write access
    mov dx,0102 ;Points to filename
    int 21 ;Do it
    mov bx,ax ;Move file handle to BX for 3e function ——-+
    mov ax,3e00H ;Close file function <————————/
    int 21 ;Do it
    end apaga

    so with this code i can close the file data if it is in the same folder?, i have used it and it didn´t work, need help

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: