问题
I am trying to write a code that read and write text file with interrupt 21h.
here is my code:
IDEAL
MODEL small
STACK 100h
DATASEG
filename db 'testfile.txt',0
filehandle dw ?
Message db 'Hello world!'
ErrorMsg db 'Error', 10, 13,'$'
CODESEG
proc OpenFile
; Open file for reading and writing
mov ah, 3Dh
mov al, 2
mov dx, offset filename
int 21h
jc openerror
mov [filehandle], ax
ret
openerror:
mov dx, offset ErrorMsg
mov ah, 9h
int 21h
ret
endp OpenFile
proc WriteToFile
; Write message to file
mov ah,40h
mov bx, [filehandle]
mov cx,12
mov dx,offset Message
int 21h
ret
endp WriteToFile
proc CloseFile
push ax
push bx
; Close file
mov ah,3Eh
mov bx, [filehandle]
int 21h
pop bx
pop ax
ret
endp CloseFile
start:
mov ax, @data
mov ds, ax
; Process file
call OpenFile
call WriteToFile
call CloseFile
quit:
mov ax, 4c00h
int 21h
END start
Why does it not working??
回答1:
proc OpenFile ; Open file for reading and writing mov ah, 3Dh mov al, 2 mov dx, offset filename int 21h jc openerror mov [filehandle], ax ret openerror: mov dx, offset ErrorMsg mov ah, 9h int 21h ret <--- This is an extra problem! endp OpenFile
It's your program that displays the message 'Error' on screen.
It does so because in the OpenFile proc, the DOS function 3Dh returned with the carry flag set. This happens most probably because the file wasn't found, simply because it didn't exist already!
To get you started, change the program to include a CreateFile proc. Remember to change the call OpenFile
into call CreateFile
.
proc CreateFile
mov dx, offset filename
xor cx, cx
mov ah, 3Ch
int 21h
jc CreateError
mov [filehandle], ax
ret
CreateError:
mov dx, offset ErrorMsg
mov ah, 9h
int 21h
jmp Quit <--- Solution to the extra problem!
endp CreateFile
Do notice that when an error is reported by DOS, it's not enough to just display a message and then happily continu with the program using ret
.
You need to abandon the program because subsequent actions would not be successful anyway.
The DOS functions 40h (WriteToFile) and 3Eh (CloseFile) also report possible errors via the CF. Make sure to catch that carry in a similar fashion.
来源:https://stackoverflow.com/questions/49843918/i-dont-understand-why-my-program-isnt-working