Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
816 views
in Technique[技术] by (71.8m points)

assembly - I don't understand why my program isn't working

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??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...