Write a procedure that reads a text-paragraph from a file and then prints the number of characters on the screen.
# MIPS assembler
# Mars simulator
#------------------------------
.data
fnf: .ascii "The file was not found: "
newL: .asciiz " "
# file_name_holder: the string that represents the file name
file_name_holder: .asciiz "1.txt"
descriptorScr: .word 0
# dat_buff : the buffer that you use to hold data (MAXIMUM: 300 bytes)
dat_buff: .space 300
.text
main:
# Open File (read-only)
li $v0, 13 # Set $v0 to 13 for system call to open file
la $a0, file_name_holder # Load file to read, $a0 set to address of string
# containing file name
li $a1, 0 # Set read-only flag
li $a2, 0 # Set mode
syscall # the file descriptor will be returned in $v0
blt $v0, 0, err # if failed to open file
la $s0, descriptorScr
sw $v0, 0($s0) # Save file descriptor in $v0 to descriptorScr
jal read_file # function READ file
add $a0,$zero,$v0 # $a0 contain number of characters (bytes) read
li $v0,1 # print number of characters (bytes) read
syscall
# Close Files
close:
la $s0, descriptorScr # file descriptor in descriptorScr
lw $a0, 0($s0) # Load File Descriptor
li $v0, 16 # Set $v0 to 16 for system call to close file
syscall
j done
# Error
err:
li $v0, 4 # System call to print string
la $a0, fnf # Load Error String
syscall
# Done
done:
li $v0, 10 # Exit Syscall
syscall
#------------------------------------------------
# function read file
# These function read text from the file to buffer
# output $v0 number bytes
read_file:
li $v0, 14 # Set $v0 to 14 for system call to read file
la $t0, descriptorScr # file descriptor in descriptorScr
lw $a0, 0($t0) # Load File Descriptor
la $a1, dat_buff # Set $a1 to address of input dat_buff
li $a2, 300 # Set $a2 to number of characters to read
syscall # $v0 will contain number of characters (bytes) read
# $v0 number bytes
jr $ra # jump to parent call
Comments
Leave a comment