CREATING AND WRITING FILES
Code Example
section .data
pathname db "path/to/file.txt"
msg db "Hello, World!", 0AH,0DH, "$"
section .text
global main
main:
; open file
mov eax, 5
mov ebx, pathname
; create file if it doesn't exist
mov ecx, 101o
mov edx, 0700o
int 80h
; write to file
mov ebx, eax
mov eax, 4
mov ecx, msg
mov edx, 16
; exit program
mov eax, 1
mov ebx, 0
int 80h
Create and Read Flags
I need to combine flags using the or operator or use the combined value directly. For example, 101o is equivalent to O_CREAT | O_WRONLY.
O_CREAT = 0100
O_WRONLY = 0001
or ---------------
0101
The way I declare 0101 in octal:
- Exclude the leading zero
101; - Append a lowercase
oto the number101oto indicate octal format;
Visual Studio Code usually shows the value directly if I hover over the flag or I can check these values directly in stat.h.
File Permission Flags
S_IRUSR = 0400
S_IWUSR = 0200
S_IXUSR = 0100
or --------------
0700
S_IRUSRis the read permission for the owner;S_IWUSRis the write permission for the owner;S_IXUSRis the execute permission for the owner;0700is the combination of these permissions;
To sum it up, or is adding the values together.
Open/Create File
eaxregister with the value5to indicate theopensyscall;ebxregister with the file path;ecxregister with the value101ofor flagscreateandwrite;edxregister with the value0700ofor permissions likerwx;int 80hto invoke the syscall;
Write to File
eaxregister with the value4to indicate thewritesyscall;ebxregister with the file descriptoreaxobtained from theopensyscall;ecxregister with the data to be writtenmsg;edxregister with the size of the data to write16;
Exit Program
eaxregister with the value1to indicate theexitsyscall;ebxregister with the value0to indicate successful execution;