This is Open, read, print, close file example v2. Launch EzMIPS, copy the following MIPS code and paste it into EzMIPS. Assemble, Run.
# ----------------------------------------------------------- #
.data
filename: .asciiz "test.txt" #file name
szfilenotfound: .asciiz "'Error. File not found'"
textSpace: .space 1050 #space to store string
.text
main:
# ----------------------- open the file --------------------- #
li $v0, 13 # open a file
li $a1, 0 # file flag (read)
la $a0, filename # load file name
add $a2, $zero, $zero # file mode (unused)
syscall
bne $v0, $zero, readfile
la $a0, szfilenotfound # address of error message
li $v0, 4 # print string
syscall
j end
# ---------------- read file text and put it in buffer ------ #
readfile:
move $a0, $v0 # load file descriptor
move $a3, $v0 # file descriptor for later use!
li $v0, 14 # read from file
la $a1, textSpace # adrress of buffer
li $a2, 1050 # number of bytes to be read
syscall
# ------------- print file text already in buffer ----------- #
la $a0, textSpace # address of string to be printed
li $v0, 4 # print string
syscall
# --------------------- close the file ---------------------- #
move $a0, $a3 # $a3 kept the file descriptor
li $v0, 16
syscall
# ---------------------- exit program ------------------------ #
end:
li $v0, 10
syscall
Please let me know of any suggestions or bugs regarding the code above.
Regards,
Antonis
# ----------------------------------------------------------- #
.data
filename: .asciiz "test.txt" #file name
szfilenotfound: .asciiz "'Error. File not found'"
textSpace: .space 1050 #space to store string
.text
main:
# ----------------------- open the file --------------------- #
li $v0, 13 # open a file
li $a1, 0 # file flag (read)
la $a0, filename # load file name
add $a2, $zero, $zero # file mode (unused)
syscall
bne $v0, $zero, readfile
la $a0, szfilenotfound # address of error message
li $v0, 4 # print string
syscall
j end
# ---------------- read file text and put it in buffer ------ #
readfile:
move $a0, $v0 # load file descriptor
move $a3, $v0 # file descriptor for later use!
li $v0, 14 # read from file
la $a1, textSpace # adrress of buffer
li $a2, 1050 # number of bytes to be read
syscall
# ------------- print file text already in buffer ----------- #
la $a0, textSpace # address of string to be printed
li $v0, 4 # print string
syscall
# --------------------- close the file ---------------------- #
move $a0, $a3 # $a3 kept the file descriptor
li $v0, 16
syscall
# ---------------------- exit program ------------------------ #
end:
li $v0, 10
syscall
Please let me know of any suggestions or bugs regarding the code above.
Regards,
Antonis
No comments:
Post a Comment