繁体   English   中英

NASM,读取文件并打印内容

[英]NASM, read a file and print the content

我在NASM(适用于Linux)中有这段代码,应该打开一个现有文件,读取该文件并在屏幕上打印内容,但不起作用,有人可以告诉我我在做什么错吗?( hello.txt是文件名)

section .data

file db "./hello.txt", 0

len equ 1024

section .bss 

buffer: resb 1024


section .text

global _start

_start:

    mov ebx, [file] ; name of the file  
    mov eax, 5  
    mov ecx, 0  
    int 80h     

    mov eax, 3  
    mov ebx, eax
    mov ecx, buffer 
    mov edx, len    
    int 80h     

    mov eax, 4  
    mov ebx, 1
    mov ecx, buffer 
    mov edx, len    
    int 80h     

    mov eax, 6  
    int 80h     

    mov eax, 1  
    mov ebx, 0 
    int 80h
mov ebx, [file] ; name of the file  
mov eax, 5  
mov ecx, 0  
int 80h     

是错的。 松开file周围的方括号。 您正在传递文件名,而不是指向文件名的指针。

mov ebx, file ; const char *filename
mov eax, 5  
mov ecx, 0  
int 80h     

我在这里看到很多错误,依次是:

mov ebx, [file] ; name of the file  
mov eax, 5  
mov ecx, 0  
int 80h

如前所述,您必须丢失方括号(因为该函数需要一个指针而不是一个值)

mov eax, 3  
mov ebx, eax
mov ecx, buffer 
mov edx, len    
int 80h

在这里,您必须先保存eax的文件描述符,然后再写入值3,否则您只需松开它即可

mov eax, 4  
mov ebx, 1
mov ecx, buffer 
mov edx, len    
int 80h

好。 在这里,您使用ebx寄存器,所以更好的方法是将文件描述符保存在内存中。 为了显示,您从缓冲区中取出了1024个字节,这是不正确的。 从文件读取后,eax寄存器将包含读取的字符数,因此从文件读取后,最好将来自eax寄存器的值存储在edx中

mov eax, 6  
int 80h

再次。 U关闭文件,但是ebx包含污垢,尽管它必须包含文件描述符

正确的代码必须如下所示:

section .data
  file db "text.txt",0 ;filename ends with '\0' byte
section .bss
  descriptor resb 4 ;memory for storing descriptor
  buffer resb 1024
  len equ 1024
section .start
global _start
_start:
  mov eax,5 ;open
  mov ebx,file ;filename
  mov ecx,0 ;read only
  int 80h ;open filename for read only

  mov [descriptor],eax ;storing the descriptor

  mov eax,3 ;read from file
  mov ebx,[descriptor] ;your file descriptor
  mov ecx,buffer ;read to buffer
  mov edx,len ;read len bytes
  int 80h ;read len bytes to buffer from file

  mov edx,eax ;storing count of readed bytes to edx
  mov eax,4 ;write to file
  mov ebx,1 ;terminal
  mov ecx,buffer ;from buffer
  int 80h ;write to terminal all readed bytes from buffer

  mov eax,6 ;close file
  mov ebx,[descriptor] ;your file descriptor
  int 80h ;close your file

  mov eax,1
  mov ebx,0
  int 80h

这不是一个完美的代码,但它应该可以工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM