← Back to Home

Practical 12

To perform file operations like open, read, write, close using INT 21H.

Theory

  1. Which DOS interrupt is used for file operations in assembly language?
  2. How do you create a new file using INT 21H?
  3. What is the purpose of the file handle returned by DOS after opening or creating a file?
  4. How can you write data to a file using assembly and DOS interrupts?
  5. Why is it important to close a file after performing file operations in assembly?

Code

Create a file named exp12.asm in Notepad and save it in D:\TASM:

.model small 
.stack 100h 
.data 
  filename db "TEST.TXT", 0 
  handle dw ? 
  buffer db "Hello, File!$" 
.code 
main proc 
  mov ax, @data 
  mov ds, ax 
 
  ; Create file 
  mov ah, 3Ch 
  xor cx, cx 
  lea dx, filename 
  int 21h 
  mov handle, ax 
 
  ; Write to file 
  mov ah, 40h 
  mov bx, handle 
  lea dx, buffer 
  mov cx, 13 
  int 21h 
 
  ; Close file 
  mov ah, 3Eh 
  mov bx, handle 
  int 21h 
mov ah, 4ch 
int 21h 
main endp 
end main 

    

Compilation and Execution using TASM

Inside DOSBox, compile and run:

    tasm filename.asm
    tlink filename.obj
    

Using Debug Tool

Run Debug:

td filename.exe
; Open file for reading
mov ah, 3Dh
mov al, 00h     ; Read-only mode
lea dx, filename
int 21h
mov handle, ax

; Read from file
mov ah, 3Fh
mov bx, handle
lea dx, buffer
mov cx, 13      ; Number of bytes to read
int 21h
    

File Operation Modes

Error Handling

Always check the carry flag after file operations:

int 21h
jc error_handler    ; Jump if carry flag is set (error occurred)
; Continue with normal execution
    

Practical Applications

  1. Creating log files for system monitoring
  2. Storing configuration data
  3. Data backup and recovery operations
  4. File-based inter-process communication

Important Notes

Remember: Always close files after operations to free system resources and ensure data integrity. File handles are limited system resources.