How to read a character from standard input in DOS such that redirection works?

Viewed 925

I am currently writing a DOS program. In this program, I use service 21/AH=01 to read a character from standard input. However, it appears that when I redirect standard input from a file, EOF detection does not work as expected. I wrote this sample program in nasm syntax to illustrate the issue:

    org 0x100

    ; read characters and sum them up
main:   xor bx,bx

.1: mov ah,1
    int 0x21
    xor ah,ah
    add bx,ax
    cmp al,0x1a       ; eof reached?
    jnz .1

    mov cx,4
.2: mov si,bx
    shr si,12
    mov dl,[hextab+si] ; convert to hex
    mov ah,2
    int 0x21
    shl bx,4
    loop .2

    ret

hextab: db '0123456789ABCDEF'

When I redirect standard input from a file, the program hangs unless that file contains a ^Z somewhere. I was under the impression that EOF is marked with service 21/AH=01 returning ^Z in DOS, however, that does not seem to be the case.

How do I read a character from standard input in DOS in a way that works with redirected stdin such that the character is echoed to the screen in case input is not redirected and such that I can detect an EOF condition? Ideally, I would like to have something that behaves like the getchar() function.

1 Answers
Related