To write data to a file in RISC-V assembly using the RARS (RISC-V
Assembler and Runtime System) simulator, you must execute three
standard environment calls (ecall): Open File (1024), Write to
File (64), and Close File (57).
a0 = File descriptor
a1 = Address of output data
buffer
a2 = Number of bytes/
characters to write
Number of bytes written
(-1 if error)
3
Close File
57
a0 = File descriptor
None
Code Example
.data
filename: .asciz "output.txt" # Null-terminated file name string
buffer: .ascii "Hello, World!\n" # The text contents to write
buffer_len: .word 14 # Length of the text buffer
.text
.globl main
main:
# -------------------------------------------------------------
# STEP 1: Open the file for writing
# -------------------------------------------------------------
li a7, 1024 # RARS system call for open file
la a0, filename # Load address of the filename string
li a1, 1 # Flag 1 = Write mode (creates file if missing)
ecall # Execute call; file descriptor returned in a0
bltz a0, file_error # If a0 < 0, there was an opening error
mv s6, a0 # Save the file descriptor safely in s6
# -------------------------------------------------------------
# STEP 2: Write text data to the file
# -------------------------------------------------------------
li a7, 64 # RARS system call for write to file
mv a0, s6 # Pass the saved file descriptor
la a1, buffer # Pass the address of the text buffer
lw a2, buffer_len # Pass the length of the string to write
ecall # Execute call
# -------------------------------------------------------------
# STEP 3: Close the file
# -------------------------------------------------------------
li a7, 57 # RARS system call for close file
mv a0, s6 # Pass the file descriptor to close
ecall # Execute call
exit_program:
# Exit system call cleanly
li a7, 93 # System call for exit (preferred over 10)
li a0, 0 # Return status 0 (success)
ecall
file_error:
# Handle error branch (e.g., directory permission issues)
li a7, 93 # Exit program
li a0, 1 # Return status 1 (error)
ecall