2011-10-07 35 views
0

我设法构建了用于处理文件的NASM教程代码。它将文件的内容输出到stdout中,但是当我尝试访问数据缓冲区时,它只包含零。例如,在中间循环下面的代码中,EBX始终设置为0,当它包含文件字节时。nasm中的文件读取缓冲区为空

section .data 
    bufsize dw  1024 

section .bss 
    buf  resb 1024 


section .text    ; declaring our .text segment 
    global _start   ; telling where program execution should start 

_start:      ; this is where code starts getting exec'ed 

    ; get the filename in ebx 
    pop ebx    ; argc 
    pop ebx    ; argv[0] 
    pop ebx    ; the first real arg, a filename 

    ; open the file 
    mov eax, 5   ; open(
    mov ecx, 0   ; read-only mode 
    int 80h    ;); 

    ; read the file 
    mov  eax, 3   ; read(
    mov  ebx, eax  ; file_descriptor, 
    mov  ecx, buf  ; *buf, 
    mov  edx, bufsize ; *bufsize 
    int  80h    ;); 

    mov ecx, 20 
loop: 
    mov eax, 20 
    sub eax, ecx 
    mov ebx, [buf+eax*4] 
    loop loop  

    ; write to STDOUT 
    mov  eax, 4   ; write(
    mov  ebx, 1   ; STDOUT, 
    mov  ecx, buf  ; *buf 
    int  80h    ;); 

    ; exit 
    mov eax, 1   ; exit(
    mov ebx, 0   ; 0 
    int 80h    ;); 
+0

伟大的评论风格! – divinci

回答

1

例如在中间环EBX下面的代码总是被设置为0,当它应该包含文件的字节。

你是如何确定的? (一个调试器下运行,也许?)

你的代码中有一个不幸的错误:

; read the file 
    mov  eax, 3   ; read(
    mov  ebx, eax  ; file_descriptor, 

你覆盖EAX(其中包含由系统调用open返回的文件描述符,如果open成功)与值3,在它被移动到EBX作为read的文件描述符参数之前。

通常情况下,一个进程将开始了文件描述符0,1和分配2 stdinstdoutstderr,且第一个文件的描述符,明确open将是3,那么你会用它跑了!

但是如果你使用调试器运行,你可能不那么幸运。文件描述符3可能是别的东西,而read可能会失败(你不检查,看看如果返回的值是一个负的错误代码),或读一些完全出乎意料......

+0

好吧,我明白了。现在读取返回正值,但buf再次不包含字符数据。 – bvk256

+0

由于这个答案解决了这个问题http://stackoverflow.com/questions/5803301/printing-character-from-register我加载一个DWORD到ebx中并掩盖额外的位来创建一个字节。 – bvk256

+0

此外,'bufsize'被声明为'dw' - 你想'dd' ...和'[bufsize]'来访问它的值。 –