如何在汇编程序中打开文件并进行修改?

Ram*_*ama 3 linux x86 assembly nasm

我开始学习汇编程序,我在Unix工作.我想打开一个文件并在上面写上"Hello world".

section.data

textoutput db 'Hello world!', 10
lentext equ $ - textoutput
filetoopen db 'hi.txt'

section .text
global _start

_start:

mov eax, 5            ;open
mov ebx, filetoopen
mov ecx, 2            ;read and write mode
int 80h

mov eax, 4
mov ebx, filetoopen   ;I'm not sure what do i have to put here, what is the "file descriptor"?
mov ecx, textoutput
mov edx, lentext

mov eax, 1
mov ebx, 0
int 80h              ; finish without errors
Run Code Online (Sandbox Code Playgroud)

但是当我编译它时,它什么也没做.我究竟做错了什么?当我打开一个文件描述符值返回的文件?

Mat*_*ery 16

这是x86 Linux(x86不是唯一的汇编语言,Linux不是唯一的Unix!)...

section .data

textoutput db 'Hello world!', 10
lentext equ $ - textoutput
filetoopen db 'hi.txt'
Run Code Online (Sandbox Code Playgroud)

文件名字符串需要一个0字节的终结符: filetoopen db 'hi.txt', 0

section .text
global _start

_start:

mov eax, 5            ;open
mov ebx, filetoopen
mov ecx, 2            ;read and write mode
Run Code Online (Sandbox Code Playgroud)

2是系统调用的O_RDWR标志open.如果您想要创建文件(如果它尚不存在),您还需要该O_CREAT标志; 如果指定O_CREAT,则需要第三个参数,即文件的权限模式.如果你在C标题中徘徊,你会发现它O_CREAT被定义为0100- 谨防前导零:这是一个八进制常量!您可以nasm使用o后缀编写八进制常量.

所以你需要一些东西mov ecx, 0102o来获得正确的旗帜并mov edx, 0666o设置永久性.

int 80h
Run Code Online (Sandbox Code Playgroud)

传入系统调用的返回码eax.这里,这将是文件描述符(如果打开成功)或小负数,这是负errno代码(例如-1表示EPERM).请注意,从原始系统调用返回错误代码的约定与C syscall包装器(通常在发生错误时返回并设置)完全相同...-1errno

mov eax, 4
mov ebx, filetoopen   ;I'm not sure what do i have to put here, what is the "file descriptor"?
Run Code Online (Sandbox Code Playgroud)

...所以在这里你需要mov ebx, eax先(openeax覆盖之前保存结果)然后mov eax, 4.(您可能想要先考虑检查结果是否为正,如果不是,则考虑以某种方式打开失败.)

mov ecx, textoutput
mov edx, lentext
Run Code Online (Sandbox Code Playgroud)

int 80h在这里失踪.

mov eax, 1
mov ebx, 0
int 80h              ; finish without errors
Run Code Online (Sandbox Code Playgroud)

  • 很棒的答案!我只是想提一下open的标志可以在debian/ubuntu上的`/ usr/include/bits/fcntl.h`中找到,[这里是常量的要点](https://gist.github.com/ Zhangerr/6022492) (2认同)