File I/O

open

Syscall 2 (open) takes a filename, flags, and a mode. The flags are constants from fcntl.h: O_RDONLY is 0, O_WRONLY is 1, O_CREAT is 0x40, O_TRUNC is 0x200:

%define SYS_OPEN 2 %define O_RDONLY 0 mov rax, SYS_OPEN mov rdi, filename mov rsi, O_RDONLY syscall ; rax = file descriptor

read

Syscall 0 (read) takes the descriptor, a buffer, and a count, and returns the bytes read. Zero means end of file, and a negative value means an error:

%define SYS_READ 0 mov rax, SYS_READ mov rdi, fd mov rsi, buf mov rdx, buflen syscall ; rax = bytes read

close

Syscall 3 (close) releases the descriptor. Close every descriptor you open, including on the error path, or the process runs out of descriptors. Write (syscall 1) works exactly like the stdout version, with the descriptor in RDI.

Next: Command-line arguments

Article author: Arthur Isaev

Banner image