16位汇编对磁盘文件管理——文件内容追加

157 阅读2分钟

16位汇编源码

功能:将一个文件的内容,追加到另一个文件结尾

准备test.txt和test1.txt文件,test.txt的内容位"hello Assembly!",test1.txt的内容为"123456789"

效果:test.txt的内容为"hello Assembly!123456789"

assume cs:code,ds:data

bufflen=512
data segment
    file1 db 'test.txt',0
    file2 db 'test1.txt',0
    handl1 dw 0
    handl2 dw 0
    openerr db 'Open error',07h,0
    readerr db 'read error',07h,0
    writeerr db 'write error',07h,0
    buffer db bufflen dup(0)
data ends

code segment
    start:
        mov ax,data
        mov ds,ax

        mov ax,3d01h ;只读方式打开
        mov dx,offset file1
        int 21h
        jc openerr1
        mov handl1,ax ;保存文件1句柄

        mov ax,3d00h
        mov dx,offset file2
        int 21h
        jc openerr2
        mov handl2,ax ;保存文件2句柄

        mov bx,handl1
        xor cx,cx
        xor dx,dx
        mov ax,4202h ;移动文件1的指针到文件尾
        int 21h

    next:
        mov bx,handl2
        mov dx,offset buffer
        mov cx,bufflen
        mov ah,3fh ;读取文件2
        int 21h

        jc readerr1
        or ax,ax ;判断是否读取完
        jz read_err

        mov cx,ax ;写到文件1的长度等于读出的长度
        mov bx,handl1
        mov dx,offset buffer
        mov ah,40h ;写入文件1
        int 21h
        jc werror ;写正确,继续
        jmp next

    werror:
        mov dx,offset writeerr
        call showmsg
        jmp read_err

    read_err:
        mov bx,handl1		;关闭文件1
        mov ah,3eh
        int 21h
        mov bx,handl2		;关闭文件2
        mov ah,3eh
        int 21h
        jmp over

    readerr1:
        mov dx,offset readerr
        call showmsg
        mov ax,3e00h
        mov bx,offset file1
        int 21h
        jmp over

    openerr1:
        mov dx,offset openerr
        call showmsg
        mov ax,3e00h
        mov bx,offset file1
        int 21h
        jmp over

    openerr2:
        mov dx,offset openerr
        call showmsg
        mov ax,3e00h
        mov bx,offset file1
        int 21h
        jmp over
    
    over:
        mov ax,4c00h
        int 21h

    ;子程序显示一个以0结尾的字符串
    ;子程序名:showmsg
    ;入口参数si=字符串首地址
    ;出口参数无
    showmsg proc
        mov ah,09h
        int 21h
        ret
    showmsg endp

code ends
    end start

最后输出的结果如下图

image.png