简体   繁体   中英

How to read and display the contents of a text file in nasm?

I want to read and display the contents of a text file using nasm and Linux system calls. My text file is named "new.txt". I wrote the following code and am receiving no output on the terminal.

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

When you write

    jb close        ;must close file first

you, in fact, are jumping to close, not calling it.

Once you reach close, you just exit after you close the file:

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

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

Perhaps you want to either call close in some way (and then ret from close) or jump back to where you were to continue what you were doing?

Also, keep in mind that jbe is an unsigned comparison, so when you write:

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

You in fact will not detect negative numbers. Consider jle instead. (You can consult this handy resource about jumps to use.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM