Search code examples
assemblyx86-16file-reademu8086

Read file in 8086 until the end of the file


MOV AH,3DH
MOV DX,OFFSET(FNAME)
MOV AL,0  ; 0 MEAN FOR READING PURPOSE             ;OPEN
INT 21H
MOV HANDLE,AX 

MOV AH,3FH
MOV BX,HANDLE
MOV DX,OFFSET(BUFFER)                            ;READ
MOV CX,30
INT 21H

MOV AH,3EH
MOV DX,HANDLE                                     ;CLOSE
INT 21H 

Now here the program reads only 30 letters from the file. I need is to read the whole file without knowing how many letters in it so how much letter it has the program will read them all.


Solution

  • MOV AH,3FH
    MOV BX,HANDLE
    MOV DX,OFFSET(BUFFER)                            ;READ
    MOV CX,30
    INT 21H
    

    This is the code that you need to replace with a loop that reads successive chunks of the file until there is nothing left.

    The 3Fh DOS call not only informs you via the carry flag about possible errors, but it also returns in the AX register the number of bytes that were actually read.

    ReadMore:
        mov dx, offset BUFFER
        mov cx, 5           ; Your chunk apparently has 5 bytes
        mov bx, HANDLE
        mov ah, 3Fh         ; DOS.ReadFile
        int 21h             ; -> AX CF
        jc  ReadError
        cmp ax, cx          ; Compares RECEIVED BYTES with REQUESTED BYTES
        jb  PartialRead
    WholeChunk:
    
        ... Whatever you need to do with 5 bytes ...
    
        jmp     ReadMore
    PartialRead:
        test    ax, ax
        jz      EndOfFile
    PartialChunk:
    
        ... Whatever you can do with 1, 2, 3, or 4 left-over bytes ...
    
    EndOfFile:
        mov bx, HANDLE
        mov ah, 3Eh         ; DOS.CloseFile
        int 21h
        ...
    

    Please notice the typo in next snippet. The handle goes in the BX register!

    MOV AH,3EH
    MOV DX,HANDLE                                     ;CLOSE
    INT 21H