0

I am trying to write an assembly program that take in a string from the file text.txt. Then the program encoded the string in ROT13 and using printf to display the result. However, It seem like i failed to read the file and get put in an infinite loop in "nextChar:" . I'm sure I miss something but not sure what it is.

Thank you

;%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
Carlos Frank
  • 167
  • 2
  • 13

1 Answers1

1

You have a loop that will be exited if getchar returns 0. If your file never has a zero byte in it this won't happen. Instead, getchar will continue to return EOF and your loop will go on indefinitely.

Check the value of EOF in your environment (usually -1, but always outside the range 0-255) and use that as the limiter for the loop.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74