程序集8086:附加在文件末尾

时间:2014-12-04 03:37:31

标签: assembly

我知道这是一个简单的问题,但我真的不知道如何解决这个问题。 我正在使用此代码

mov bx, handle
mov dx, offset data
mov cx, 100
mov ah, 40h
int 21h

写入文件。但我需要“更新”它;有点像追加到它的末尾。可能吗?如果是这样,我该怎么做?有没有具体的指示呢?谢谢!

这是我的代码:

.model small
.data
    filename db "test1.txt", 0
    handle dw ?
    data db "write me! "
    buffer db 200 dup(' ') 
    errormess db "Error in opening file!$"
.stack 100h
.code

    main proc

    mov ax, @data
    mov ds, ax

    mov AH,3dh
    mov AL,2
    lea dx,filename
    int 21h

    mov handle,AX
    jc erroropen
    jmp noerror
    erroropen:
        lea dx, errormess
        mov ah, 09h
        int 21h
        jmp exit
    noerror:

    mov bx, handle
    mov ah, 42h  ; "lseek"
    mov al, 2    ; position relative to end of file
    mov cx, 0    ; offset MSW
    mov dx, 0    ; offset LSW
    int 21h

    ;mov bx, handle
    mov dx, offset data
    mov cx, 100
    mov ah, 40h
    int 21h ; write to file...

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

    exit:
    mov ax, 4c00h
    int 21h

    main endp
    end main

1 个答案:

答案 0 :(得分:2)

也许在编写之前使用function 42hlseek)并定位到文件的末尾:

; assuming "bx" holds the file handle

mov ah, 42h  ; "lseek"
mov al, 2    ; position relative to end of file
mov cx, 0    ; offset MSW
mov dx, 0    ; offset LSW
int 21h

; current position (= file length) now in dx:ax
; write here...

(哇,我以为我再也没想过DOS中断了; - )。

更新:使用nasm进行汇总(您必须调整语法),并使用dosemu进行测试:

   org 100h

section .code

start:
   mov ah, 3dh
   mov al, 2
   mov dx, filename
   int 21h
   jc err_open

   mov [handle], ax

   mov bx, ax
   mov ah, 42h  ; "lseek"
   mov al, 2    ; position relative to end of file
   mov cx, 0    ; offset MSW
   mov dx, 0    ; offset LSW
   int 21h
   jc err_seek

   mov bx, [handle]
   mov dx, usermsg
   mov cx, 100
   mov ah, 40h
   int 21h ; write to file...
   jc err_write

   mov bx, [handle]
   mov ah, 3eh
   int 21h ; close file...
   jc err_close

exit:
   mov ax, 4c00h
   int 21h

err_open:
   mov dx, msg_open
   jmp error

err_seek:   
   mov dx, msg_seek
   jmp error

err_write:
   mov dx, msg_write
   jmp error

err_close:
   mov dx, msg_close
   ; fallthrough

error:
   mov ah, 09h
   int 21h

   mov ax, 4c01h
   int 21h


section .data

filename:  db "test1.txt", 0
handle:    dw 0
usermsg:   db "write me", 0
buffer:    times 200 db 0
msg_open:  db "Error opening file!$"
msg_seek:  db "Error seeking file!$"
msg_write: db "Error writing file!$"
msg_close: db "Error closing file!$"

今晚可能比我想要的DOS更多: - )

% echo "bla" > ~/.dosemu/drive_c/test1.txt 
% dosemu

enter image description here