Reading txt file using stdin in assembly

I'm learning assembly right now. Could someone explain how I read a textile using stdin in x86-64 NASM Assembly and where do I store the read ascii symbols?


Solution 1:

I'll assume you are using linux for this one. First of all, you'll need to open the file with the open syscall. This will put the file descriptor to %rax. Then, you can use that file descriptor for the read syscall along with how many bytes you want to read. Lastly you'll want to close the file with the close syscall using the file descriptor of the file. An example might look something like this:

;; reading from a file using syscalls

global _start

section .text
_start:
        mov rax, 2 ;; using the open syscall
        mov rdi, filename
        mov rsi, 0 ;; using O_RDONLY
        syscall

        mov rbx, rax ;; storing the fd for later

        mov rax, 0 ;; read syscall
        mov rdi, rbx ;; the file descriptor
        mov rsi, buffer
        mov rdx, 13 ;; bytes to read
        syscall

        mov rax, 1 ;; write syscall
        mov rdi, 1 ;; stdout
        mov rsi, buffer
        mov rdx, 13
        syscall

        mov rax, 3 ;; using the close syscall
        mov rdi, rbx
        syscall

        mov rax, 60
        mov rdi, 0
        syscall

section .data
filename: db "file.txt", 0x0

section .bss
buffer: resb 13

file.txt:

hello world