【问题标题】:How to read and display the contents of a text file in nasm?如何在 nasm 中读取和显示文本文件的内容?
【发布时间】:2015-09-27 11:43:11
【问题描述】:

我想使用 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

【问题讨论】:

    标签: linux nasm system-calls file-handling


    【解决方案1】:

    当你写作时

        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。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-22
      • 2013-06-17
      • 2010-12-01
      • 1970-01-01
      • 2012-07-26
      • 1970-01-01
      • 2014-11-23
      相关资源
      最近更新 更多