【问题标题】:Assembly Language modify input string;汇编语言修改输入字符串;
【发布时间】:2016-04-06 09:25:55
【问题描述】:

我正在尝试编写一个从文件 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

【问题讨论】:

  • 什么时候出现无限循环?

标签: file assembly x86 nasm libc


【解决方案1】:

如果getchar 返回0,您将退出一个循环。如果您的文件中从来没有零字节,这不会发生。相反,getchar 将继续返回 EOF,您的循环将无限期地继续。

检查您环境中EOF 的值(通常为-1,但始终在0-255 范围之外)并将其用作循环的限制器。

【讨论】:

    猜你喜欢
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 2015-05-04
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多