In: Computer Science
Write a MIPS Assembly language program to request a file name from the user, open the file, read the contents, and write out the contents to the console.
This is what I have so far:
.data
fileName: .space 100
prompt1: .asciiz "Enter the file name:
"
prompt2: .asciiz ""
prompt3: .asciiz "\n"
buffer: .space 4096
.text
main:
#
li $v0, 4
la $a0, prompt1
syscall
#
li $v0, 8
la $a0, fileName
li $a1, 50
syscall
jal remove
#
li $v0, 13
la $a0, fileName
li $a1, 0
li $a2, 0
syscall
move $s0, $v0
#
li $v0, 14
move $a0, $s0
la $a1, buffer
li $a2, 11
syscall
#
li $v0, 4
la $a0, buffer
syscall
#
li $v0, 10
syscall
Note: My jar file and text file located in the same folder, please input full path for getting results
FileOperation.asm:
.data
fileName: .space 100
prompt1: .asciiz "Enter the file name: "
buffer: .space 40966
.text
main:
#
li $v0, 4
la $a0, prompt1
syscall
#(the file name must be full path or path from which Mars jar file
is located)
li $v0, 8
la $a0, fileName
li $a1, 50
syscall
# converting the string into a null-terminated string
#replacing last character of fileName with 0 instead of \n
la $s0, fileName # $s0
contains base address of str
add $s2, $0, $0 # $s2 =
0
addi $s3, $0, '\n' # $s3 =
'\n'
loop:
lb $s1, 0($s0) # load
character into $s0
beq $s1, $s3, end # Break if
byte is newline
addi $s2, $s2, 1 # increment
counter
addi $s0, $s0, 1 # increment
str address
j loop
end:
sb $0, 0($s0) #replace newline
with 0
#now that input file name is converted to
null-terminated string the remaining code is same
# Open file for reading
li $v0, 13 # system call for open file
la $a0, fileName # address of null-terminated string
containing filename
li $a1, 0 # flags
li $a2, 0 # mode
syscall # open a file
move $s0, $v0 # save the file descriptor
# reading from file just opened
li $v0, 14 # system call for reading from
file
move $a0, $s0 # file descriptor
la $a1, buffer # address of input buffer
li $a2, 100 # maximum number of characters to
read
syscall # read from file
# Printing File Content
li $v0, 4 # system Call for PRINT STRING
la $a0, buffer # buffer contains the values
syscall # print int
li $v0, 10 # Finish the Program
syscall
Output: