我想使用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
最佳答案
当你写
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有关使用的跳转。)