我正在尝试编写一个汇编程序,它从文件text.txt中获取一个字符串。然后程序在ROT13中编码字符串并使用printf显示结果。但是,似乎我没有读取文件并在“nextChar:”中进入无限循环。我确定我错过了一些但不确定它是什么。
谢谢
;%include "glibc"
section .data ;section declaration
getFmt: dd "%c",10,0
fileFmt: dd "%s",10,0
countFmt: dd "%d",10,0
output: dd "output.txt",10,0
writeCode: dd "w",10,0
readCode: dd "r",10,0
EOF: db -1 ;I read that this may need to be 0, instead of -1
Filename db "text.txt",0
section .bss
char:
buf: resb 1
section .text ;section declaration
global main
extern fopen
extern fclose
extern printf ;you can use this for debugging, otherwise not needed
extern getchar
extern putchar
extern scanf
main:
mov ebx, Filename ; push file name to ebx
push readCode ;set file to "read" mode
push ebx ;push file name
call fopen ;open file
add esp,8
cmp eax,0 ;see if file opened correctly
jne nextChar
ret
nextChar:
push ebx ; Push file handle on the stack
mov ebx,eax ; Save handle of opened file in ebx push ebx
push dword [char] ;get the next char from input file
push getFmt ;
call getchar ;use getchar function
add esp,12 ;clear the stack
cmp eax,0 ; A returned null indicates error or EOF
jle done ; If we get 0 in eax, close up & return
add dword [char],13 ;add 13 to the ASCII value
push dword [char] ; push to print
push getFmt ;
call printf ;use printf function
add esp, 8 ;clear the stack
jmp nextChar
done:
push ebx ; Push the handle of the file to be closed
call fclose ; Closes the file whose handle is on the stack
add esp,4 ; Clean up the stack
ret ; Go home
答案 0 :(得分:1)
如果getchar
返回0
,您将退出循环。如果您的文件中没有零字节,则不会发生这种情况。相反,getchar
将继续返回EOF
,您的循环将无限期地继续。
检查环境中EOF
的值(通常为-1,但总是在0-255范围之外)并将其用作循环的限制器。