File Handling

In this example we will study how to create a new file, open an existing one, read from a file, write in a file and close a file.

File Descriptor

A file descriptor acts as a file id. It is a 16-bit integer assigned when a new file is created or a file is opened. It is generated in eax register.
Create an assembly file file.asm and follow along -

                                    

global _start ; must be declared for global

section .data

file_name db "data.txt", 0 ; Defining file name

msg db "This is NASM tutorial.", 0x0a ; The message

len equ $ - msg ; len equals size of msg

section .bss

fd_out resb 1 ; Unitialized data variable, file descriptor for write

fd_in resb 1 ; Unitialized data variable, file descriptor for read

info resb 26 ; Unitialized data variable info

section .text

_start: ; start label

mov eax, 8 ; sys_creat system call

mov ebx, file_name ; file name as second parameter

mov ecx, 0777 ; Setting permission for read, write and execute by all in third parameter

int 0x80 ; Perform the system call

mov [fd_out], eax ; Reading the file descriptor in fd_out from eax

mov eax, 4 ; sys_write system call

mov ebx, [fd_out] ; file descriptor fd_out

mov ecx, msg ; ecx=msg

mov edx, len ; edx=len

int 0x80 ; Perform the system call

mov eax, 6 ; sys_close system call

mov ebx, [fd_out] ; file descriptor fd_out

mov eax, 5 ; sys_open system call

mov ebx, file_name ; Setting file name to be opened

mov ecx, 0 ; for read only access

mov edx, 0777 ; Setting permission for read, write and execute by all

int 0x80 ; Perform the system call

mov [fd_in], eax ; Reading file descriptor of opened file in fd_in

mov eax, 3 ; sys_read system call

mov ebx, [fd_in] ; file descriptor fd_in

mov ecx, info ; Reading in info

mov edx, 26

int 0x80 ; Perform the system call

mov eax, 6 ; sys_close system call

mov ebx, [fd_in] ; file descriptor fd_in

mov eax, 4 ; sys_write system call

mov ebx, 1 ; stdout file descriptor

mov ecx, info ; ecx=ans

mov edx, 26

int 0x80 ; Perform the system call

mov eax , 1 ; sys_exit system call

mov ebx , 0 ; setting exit status

int 0x80 ; Calling interrupt handler to exit program


                                    

>> nasm -f elf32 file.asm -o file.o

>> ld -m elf_i386 file.o -o file

>> ./file


                                   

>> This is NASM tutorial.

This brings us to the end of tutorial.