我正在使用一个汇编库来制作一个从标准输入中读取三个整数的程序。当在控制台中完成读取时,它工作得很好,但是当我使用文件作为输入时,它会一次读取三个整数。
这是控制台的 strace:
read(0, "3000\n", 512) = 5
read(0, "2000\n", 512) = 5
read(0, "1000\n", 512) = 5
这来自输入文件:
read(0, "3000\n2000\n1000\n", 512) = 15
read(0, "", 512) = 0
read(0, "", 512) = 0
以下是程序:
;--------------------------------------------------------
ReadInt:
;
; Reads a 32-bit signed decimal integer from standard
; input, stopping when the Enter key is pressed.
; All valid digits occurring before a non-numeric character
; are converted to the integer value. Leading spaces are
; ignored, and an optional leading + or - sign is permitted.
; All spaces return a valid integer, value zero.
; Receives: nothing
; Returns: If CF=0, the integer is valid, and EAX = binary value.
; If CF=1, the integer is invalid and EAX = 0.
;--------------------------------------------------------
push edx
push ecx
; Input a signed decimal string.
mov edx,digitBuffer
mov ecx,MAX_DIGITS
call ReadString
mov ecx,eax ; save length in ECX
; Convert to binary (EDX -> string, ECX = length)
call ParseInteger32 ; returns EAX, CF
pop ecx
pop edx
ret
;--------------- End of ReadInt ------------------------
;--------------------------------------------------------
ReadString:
;
; Reads a string from the keyboard and places the characters
; in a buffer.
; Receives: EDX offset of the input buffer
; ECX = maximum characters to input (including terminal null)
; Returns: EAX = size of the input string.
; Comments: Stops when Enter key (0Dh,0Ah) is pressed. If the user
; types more characters than (ECX-1), the excess characters
; are ignored.
; Written by Kip Irvine and Gerald Cahill
; Modified by Curtis Wong
;--------------------------------------------------------
enter 8, 0 ; bufSize: ebp - 4
; bytesRead: ebp - 8
pushad
mov edi,edx ; set EDI to buffer offset
mov dword [ebp - 4],ecx ; save buffer size
call ReadKeys
mov dword [ebp - 8], eax
cmp eax,0
jz .L5 ; skip move if zero chars input
cld ; search forward
mov ecx, dword [ebp - 4] ; repetition count for SCASB
dec ecx
mov al,NL ; scan for 0Ah (Line Feed) terminal character
repne scasb
jne .L1 ; if not found, jump to L1
;if we reach this line, length of input string <= (bufsize - 2)
dec dword [ebp - 8] ; second adjustment to bytesRead
dec edi ; 0Ah found: back up two positions
cmp edi,edx ; don't back up to before the user's buffer
jae .L2
mov edi,edx ; 0Ah must be the only byte in the buffer
jmp .L2 ; and jump to L2
.L1: mov edi,edx ; point to last byte in buffer
add edi,dword [ebp - 4]
dec edi
mov byte [edi],0 ; insert null byte
; Clear excess characters from the buffer, 1 byte at a time
.L6: call BufferFlush
jmp .L5
.L2: mov byte [edi],0 ; insert null byte
.L5: popad
mov eax, dword [ebp - 8]
leave
ret
;--------------- End of ReadString --------------------