当前位置: 动力学知识库 > 问答 > 编程问答 >

nasm - How to take string input from file in assembly Language?

问题描述:

I have a file named customer.txt.

customer.txt

amin jamal

I need a sample code which takes string input(amin) from customer.txt file

and print it using c printf function.

My code is

section .bss

s: resb 100

section .data

fmt: db "%s",10,0

name: db "customer.txt",0

mode: db "r+",0

fp: dq 0

section .text

global main

extern fopen

extern fgets

extern printf

main:

push rbp

mov rdi , name;

mov rsi , mode

call fopen

mov [fp] , rax

mov rdi , s

mov rsi , 7

mov rdx , [fp]

call fgets

mov rdi , fmt

mov rsi , s

call printf

pop rbp

ret

This can not take full string.

I am using NASM assembler. My OS is 64bit Linux.

I use nasm command for assemble, compile and run.

nasm -f elf64 file.asm

gcc file.o

./a.out

网友答案:

Your code works fine for me. Can you add some error handling. I tried your code and it worked fine for me.

section .bss
s : resb 100

section .data
fmt  : db "%s",10,0
name : db "customer.txt",0
mode : db "r+",0
err1 : db "Failed To Open File", 10, 0
err2 : db "Failed To Read File", 10, 0

section .text
extern fopen
extern fgets
extern printf

global main

main:
    push rbp

    ; Open the file for reading
    mov rdi , name
    mov rsi , mode
    call fopen
    cmp rax, 0       ; Check for errors
    je .errfopen

    ; read first 7 characters from the open file
    mov rdi , s
    mov rsi , 7
    mov rdx , rax ; File Pointer
    call fgets
    cmp rax, 0    ; Check for errors
    je .errfgets

    mov rdi, fmt
    mov rsi, s
    call printf

    pop rbp
    ret

.errfopen:
    mov rdi, err1
    call printf
    pop rbp
    ret

.errfgets:
    mov rdi, err2
    call printf
    pop rbp
    ret
分享给朋友:
您可能感兴趣的文章:
随机阅读: