I am trying to read a string from a file and print it on the screen, but I always get an error at opening the file. Why is this happening? What is wrong with the code or with the file? PS: the file is in the same folder as the .asm file.

ASSUME cs: code, ds:data
data SEGMENT
    inputFile db "D:\AC\input.txt", 0
    openingError db 'An error has occured at opening the file!$'
    readingError db 'An error has occured at reading the file!$'
    s1 db 10 dup(?)
    ls db 0
    handle dw ?
data ENDS

code SEGMENT
start:
    mov ax,data
    mov ds,ax
            ;open the file
    mov ah, 3dh
    mov al, 0
    mov dx, offset inputFile
    int 21h
    mov handle, ax
    jc openError
            ;read 10 bytes from the file into s1
    mov ah, 3fh
    mov bx, handle
    mov cx, 10
    mov dx, offset s1
    int 21h
    jc readError

    openError:
        mov ah, 09h
        mov dx, offset openingError
        int 21h
        jmp the_end

    readError:
        mov ah, 09h
        mov dx, offset readingError
        int 21h
        jmp the_end

            ;close file
    mov ah, 3eh
    mov bx, handle
    int 21h

            ;print string on the screen
    lea dx, s1
    mov ah, 09h
    int 21h

    the_end:
        mov ax,4C00h
        int 21h
code ENDS
END start

Hi,
Well, it is the kind of bug that is repeated again and again.
Look at these lines:

mov dx, offset s1
int 21h
jc readError
openError:
mov ah, 09h

The program opens the file. The program reads the file and after "jc readError" it simply continues with the next line that is: "openError:" mov ah, 09h...
This can be solved simply adding after "jc readError" a simple "jmp someplaceafteropenerrorandreaderror".

Cheers.

Hi once more,

Can you test my code:

.286
.MODEL SMALL

.STACK 1024

.DATA              
    inputFile db "A:\TASM\DRIVES.ASM", 0
    openingError db 'An error has occured at opening the file!$'
    readingError db 'An error has occured at reading the file!$'

.DATA?
    s1 db 10 dup(?)
    ls db ?
    handle dw ?

.CODE
    start:
    mov ax,@data
    mov ds,ax
;open the file
    mov ah, 3dh
    mov al, 0
    lea dx, inputFile
    int 21h
    jc openError
    mov handle, ax
;read 10 bytes from the file into s1
    mov ah, 3fh
    mov bx, handle
    mov cx, 10
    mov dx, offset s1
    jc readError
    int 21h
;I put the string terminator after the bytes read:
    mov bx, offset s1
    add bx, ax
    mov byte ptr [bx], '$'
;close file
    mov ah, 3eh
    mov bx, handle
    int 21h
;print string on the screen
    lea dx, s1
    mov ah, 09h
    int 21h
the_end:
    mov ax,4C00h
    int 21h
openError:
    mov ah, 09h
    mov dx, offset openingError
    int 21h
    jmp the_end
readError:
    mov ah, 09h
    mov dx, offset readingError
    int 21h
    jmp the_end
    END start

You must change the file path.
Please, forgive my mistakes.

Cheers.

Edited 2 Years Ago by untio

This article has been dead for over six months. Start a new discussion instead.