2016-10-01 11 views
0

好吧,我沿着一个教程,我一直在抓着我的大脑了这个..我试过寻找资源,但似乎没有任何工作或点击。所有我试图做的是从文件读取输入,逐个字符地继续保存到另一个文件。 (如果你愿意的话) 现在我遇到了两个让我疯狂的主要问题。NASM汇编语言似乎不能将输出保存到文件

  1. 出于某种原因,文件的输出被打印到终端屏幕上。这真是太好了,除了这些,我写这些时并不是我想到的。它应该只写入一个文件并退出。
  2. 脚本运行之后,“输出文件”被创建,但它是空的

,即时通讯以下是在https://www.tutorialspoint.com/assembly_programming/assembly_file_management.htm

section .data 
    f_in: db "file_input.txt",0 
    f_out: db "file_output.txt",0 
section .bss 
    Buff resb 1  ;hold the value of one char 
    fd_in resb 1 
    fd_out resb 1 
section .data 
global _start 
_start: 
    nop   ;keeps gdb debugger happy 
;Creates the output file that will be used to store 
Create: 
    mov eax, 8  ;sys call, create 
    mov ebx, f_out  ;file name is ebx register 
    mov ecx, 666q  ;file permisions for the outfile in octal 
    int 80h   ;kernel call 
    mov [fd_out], eax ;mov file desc into fd_out 

;Open the input file to be read in read only mode 
;(0) = read only 
;(1) = write only 
;(2) = read write only 
Open: 
    mov eax, 5  ;sys call, open 
    mov ebx, f_in  ;file name in ebx 
    mov ecx, 0  ;file access mode (0) == read only 
    int 80h   ;kernel call 
    mov [fd_in], eax ;mov file desc into fd_in 

;Read the opened file data into Buff var declared above 
;Buff only holds 1 byte 
Read: 
    mov eax, 3  ;sys call, read 
    mov ebx, [fd_in] ;mov file desc in ebx 
    mov ecx, Buff  ;mov pointer Buff into ecx 
    mov edx, 1  ;mov Buff size into edx 
    int 80h 

    cmp eax, 0  ;check val in eax with 0 
    je Exit   ;if eax is (0 means EOF) so exit 

;write all the data encoded into the file 
Write: 
    mov eax, 4  ;sys call, write 
    mov ebx, [fd_out] ;file descriptor 
    mov ecx, Buff  ;message to write 
    mov edx, 1  ;length of message 
    int 80h 
    jmp Read  ;go back to begining and read again 

Exit: 
;close the files 
Close_files: 
    mov eax, 6  ;sys call, close 
    mov ebx, [fd_in] ;put file descriptor in ebx 
    int 80h 
    mov ebx, [fd_out] 
    int 80h 
;now exit after files are closed 
    mov eax, 1  ;sys call, exit 
    int 80h 
+0

你在使用什么API?什么平台? – wallyk

+0

我使用虚拟盒来运行一个32位的Ubuntu。不知道什么API即时使用 –

回答

3

发现fd_in resb 1fd_out resb 1你仅保留一个字节的教程为您的文件句柄。但随后你阅读和写作的整个ebx并从这些位置。 ebx是4个字节长。这不会奏效。

尝试resb 4两个文件句柄。

的东西恰恰是发生了解释:你打开输出文件,你把手存储在fd_out。文件句柄可能类似于5,所以5写在fd_out,接下来的3个字节用零清零。然后,您打开输入文件,并将句柄存储在fd_in中。该文件句柄例如是6,因此在fd_in中写入6,并且清除以下3个字节,这意味着fd_out被清除,因为它位于内存中的fd_in之后。然后,下次将fd_out加载到ebx时,您正在读取四个零字节,即0。文件句柄0显然对应于标准输出,这就是为什么所有内容都转储到屏幕上的原因。

+0

哇..就是这样..这是它..谢谢和欢呼 –

+0

你的第二节'数据'应该'节.text'和仔细检查,但正常的32位指针大小也是4-字节。 –