To read a file one line (or character) at a time in the
RARS simulator, open the file using Service 1024, and
then read from it iteratively using Service 63 (ecall).
- Open File (1024): a0 = address of null-terminated filename
string, a1 = flags (0 = read-only). Returns file descriptor in
a0 (or negative on error).
- Read from File (63): a0 = file descriptor, a1 = address of input buffer, a2 = maximum length to read. Returns number of bytes read in a0 (0 indicates EOF).
- Close File (57): a0 = file descriptor.
Because RARS file reads fill a byte buffer up to a specified length
rather than providing a built-in readline() function, the standard
approach is to read byte-by-byte or small chunks at a time,
checking for the newline character (\n, ASCII 10).
Code Example
#=================================================================
# read a file (character-by-character/Line-by-Line)
# ================================================================
.data
filename: .asciz "input.txt"
buffer: .space 2
.text
.globl main
main:
# 1. Open file for reading
li a7, 1024 # Open file ecall code
la a0, filename # Load filename address
li a1, 0 # Flags: 0 = read-only
ecall
blez a0, error # Check if file opened successfully
mv s0, a0 # Save file descriptor in s0
read_loop:
# 2. Read a single byte/character using ecall 63
li a7, 63 # Read file ecall code
mv a0, s0 # File descriptor
la a1, buffer # Buffer address
li a2, 1 # Read 1 character at a time
ecall
# 3. Check for EOF or errors
blez a0, close_file # If a0 <= 0, end of file reached
# 4. Process the character (e.g., print it or check for '\n')
li a7, 11 # Print character ecall code
lb a0, buffer # Load the read byte
ecall
j read_loop
close_file:
# 5. Close the file
li a7, 57
mv a0, s0
ecall
error:
# Exit program
li a7, 10
ecall