[英]How to save a file in assembly language with nasm in Linux x86?
我只是想知道如何向文件中添加緩沖區。 我知道我可以像這樣設置寄存器:
mov eax, 4
mov ebx, (file descriptor here)
mov ecx, myBuffer
mov edx, myBufferLen
int 80h
然后使用以下命令關閉文件:
mov eax, 6
int 80h
但我不確定如何獲取文件描述符。 有人告訴我,無論何時打開文件,在調用服務調度程序后,eax都具有文件描述符。 無論我嘗試什么,它都不會創建新文件或保存當前文件。
mov eax, 5 ; __NR_open
mov ebx, filename ; zero terminated!
mov ecx, 2 ; O_WRITE? Check me on this!
mov edx, 777q ; permissions - Check me on this, too!
int 80h
; did we succeed?
cmp eax, -4096
ja exit
mov [descriptor], eax
; and so on...
;...
xor eax, eax ; claim no error
exit:
mov ebx, eax
neg ebx
mov eax, 1 ; __NR_exit
int 80h
我不確定打開標志和權限的“魔術數字”,也懶得立即查找它們(fs.h?)。 您可能需要使用O_CREATE“或”打開標志來創建一個新文件(?)。 “退出:”的技巧可以使(否定的)ERRNO(如果有的話)無效,因此您可以使用“ echo $?”輕松地讀取它。 像這樣
感謝@gnometorule提供解決方案。 因此,這就是將緩沖區存儲到文件中的方式:在這種情況下,運行程序時,您將接收文件名作為第一個參數。
section .text
global _start
_start:
pop ebx ; this is the amount of parameter received (in this case 2)
pop ebx ; this is the direction of our program
pop ebx ; this is the first parameter (our file name eg. "text.txt")
因此我們將其打開,然后將其移至緩沖區以進行編輯或進行其他操作。
textEdit:
;we open the file
mov eax, 5
push ebx ; we save the file name in the stack for later use
mov ecx,0
int 80h
; and then we move the information read to buffer
mov eax, 3
mov ebx, eax ; really dont know how this works, but it does.
mov ecx, fileBuffer
mov edx, fileBufferSize
int 80h
現在,fileBuffer(在.bss節中定義的緩沖區)具有我們在打開的文件中擁有的內容。 您可以在此處編輯信息。 當我們想將其保存回文件時,它像這樣:
saveFile:
;open the file
mov eax, 5
pop ebx ; the file name was stored in the stack,
push ebx ; so we retrieve it and save it back for later use
mov ecx, 2 ; ecx has the access mode ("2"aloud us to read/write)
mov edx, $0666
int 80h
;now we are going to write to the file
mov ebx, eax ; eax has the file descriptor we opened. so we move it to ebx.
mov eax, 4 ; we are going to use the write service (#4)
mov ecx, fileBuffer ; ecx has the adress of what we want to write
mov edx, fileBufferSize ; edx has the amount of bytes we want to write
int 80h
; close the file
mov eax, 6
int 80h
jmp exit ; jump wherever you want, or end your program... etc.
這對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.