如何在nasm中读取和显示文本文件的内容?

时间:2015-09-27 11:43:11

标签: linux nasm system-calls file-handling

我想使用nasm和Linux系统调用来阅读和显示文本文件的内容。我的文本文件名为" new.txt"。我写了下面的代码,终端上没有输出。

section .data
    line db "This is George,",
        db " and his first line.", 0xa, 0
    len equ $ - line
    line2 db "This is line number 2.", 0xa, 0
    len2 equ $ - line2
filename:   db 'ThisIsATestFile.txt', 0

section .bss
    bssbuf: resb len    ;any int will do here, even 0,
    file: resb 4        ;since pointer is allocated anyway

global _start
section .text
_start:
; open file in read-only mode

    mov eax, 5      ;sys_open file with fd in ebx
    mov ebx, filename       ;file to be opened
    mov ecx, 0      ;O_RDONLY
    int 80h

    cmp eax, 0      ;check if fd in eax > 0 (ok)
    jbe error       ;can not open file

    mov ebx, eax        ;store new (!) fd of the same file

; read from file into bss data buffer

    mov eax, 3      ;sys_read
    mov ecx, bssbuf     ;pointer to destination buffer
    mov edx, len        ;length of data to be read
    int 80h
    js error        ;file is open but cannot be read

    cmp eax, len        ;check number of bytes read
    jb close        ;must close file first

; write bss data buffer to stderr

    mov eax, 4      ;sys_write
    push ebx        ;save fd on stack for sys_close
    mov ebx, 2      ;fd of stderr which is unbuffered
    mov ecx, bssbuf     ;pointer to buffer with data
    mov edx, len        ;length of data to be written
    int 80h

    pop ebx         ;restore fd in ebx from stack

close:
    mov eax, 6  ;sys_close file
    int 80h

    mov eax, 1  ;sys_exit
    mov ebx, 0  ;ok
    int 80h

error:
    mov ebx, eax    ;exit code
    mov eax, 1  ;sys_exit
    int 80h

1 个答案:

答案 0 :(得分:0)

写作时

    jb close        ;must close file first
事实上,你关闭,而不是叫它。

关闭后,您只需在关闭文件后退出:

close:
    mov eax, 6  ;sys_close file
    int 80h

    mov eax, 1  ;sys_exit
    mov ebx, 0  ;ok
    int 80h

也许您希望call以某种方式关闭(然后从关闭开始ret)或者跳回到您要继续做的事情的位置?

此外,请注意jbe无符号比较,所以当你写:

cmp eax, 0      ;check if fd in eax > 0 (ok)
jbe error       ;can not open file

你实际上不会检测到负数。请考虑使用jle。 (您可以参考this handy resource关于要使用的跳跃。)