我在尝试打开文件并从中读取时遇到问题 . 提示用户输入文件名 .
该程序编译没有错误,但没有显示任何内容 . 当我在 .data
部分对文件名进行硬编码时,它运行正常,但是当我从用户那里得到文件名时,它无法读取文件 . 我哪里做错了?我找不到任何错误 .
使用硬编码名称输出: welcome
用户输入名称时的输出: ���
这是我的代码:
section .data
promptUsr db 'enter a file name:',0xA,0xD
lenPrompt equ $-promptUsr
info db 1
;file_name db 'data.txt' (NOTE:harcoded name works when used)
section .bss
fd_in resb 1
buffer resb 7
file_name resb 20
section .text
global _start
_start:
;prompt user to enter a file name
mov eax,4 ;sys_write
mov ebx,1 ;stdout
mov ecx,promptUsr
mov edx,lenPrompt
int 0x80
;read filename (NOTE:when user enters the same name 'data.txt',this is the output:���)
mov eax,3
mov ebx,2
mov ecx,file_name ;(NOTE:tried using 'dword[file_name]',doesnt work)
mov edx,20
int 0x80
;open file
mov eax,5
mov ebx,file_name ;(NOTE:also tried using 'dword[file_name]',doesnt work too)
mov ecx,2 ;read n write
mov edx,7777h ;all file permissions
int 0x80
mov [fd_in],eax
;read 7 bytes of the file
mov eax,3
mov ebx,[fd_in]
mov ecx,buffer
mov edx,7
int 0x80
;close the file
mov eax,6
int 0x80
;print out what was read
mov eax,4
mov ebx,1
mov ecx,buffer
mov edx,7
int 0x80
;end program
mov eax,1
int 0x80
2 回答
添加迈克尔所说的...... 1)
fd_in
太小了 - 让它成为resd 1
. 2)sys_read
不返回以零结尾的字符串,sys_open
想要一个 .`mov byte [ecx + eax - 1], 0`
文件名的sys_read
应该零终止它 .看起来你正试图阅读
STDERR
:如果你想从
STDIN
读取,mov ebx,2
应该是mov ebx,0
.如果在没有设置
O_CREAT
标志的情况下使用sys_open
,它将失败并返回-1(如果该文件尚不存在) . 如果您愿意,也可以使用access(syscall 33)或stat(syscall 18) .