I was working on a project for my class which requires me to read in from a file line by line. Our end goal is to make a MIPS assembler using the MIPS language, but the problem pertinent to this post is that I cannot read in line by line from the file. I have created this so far as a mechanism to read in information from the file.
.data
file_loc: .asciiz "test.asm" #note: when launching from commandline, test.asm should be within the same folder as Mars.jar
buffer: .space 1024 #buffer of 1024
new_line: .asciiz "\n" #where would I actually use this?
#error strings
readErrorMsg: .asciiz "\nError in reading file\n"
openErrorMsg: .asciiz "\nError in opening file\n"
.text
main:
jal openFile
j endProgram
openFile:
#Open file for for reading purposes
li $v0, 13 #syscall 13 - open file
la $a0, file_loc #passing in file name
li $a1, 0 #set to read mode
li $a2, 0 #mode is ignored
syscall
bltz $v0, openError #if $v0 is less than 0, there is an error found
move $s0, $v0 #else save the file descriptor
#Read input from file
li $v0, 14 #syscall 14 - read filea
move $a0, $s0 #sets $a0 to file descriptor
la $a1, buffer #stores read info into buffer
li $a2, 1024 #hardcoded size of buffer
syscall
bltz $v0, readError #if error it will go to read error
li $v0, 4
la $a0, buffer
syscall
#Close the file
li $v0, 16 # system call for close file
move $a0, $s0 # file descriptor to close
syscall # close file
jr $ra
openError:
la $a0, openErrorMsg
li $v0, 4
syscall
j endProgram
readError:
la $a0, readErrorMsg
li $v0, 4
syscall
j endProgram
endProgram:
li $v0, 10
syscall
The problem is reading in a file will read in as many bytes that can be held within the buffer (1024), rather than the line.
For example reading in a file named test.asm with the following data:
test abc abc abc
test2 1231 123 123
will yield an output of:
test abc abc abc
test2 1231 123 123
Where as I am hoping to read in one line at at time:
test abc abc abc
I know that reducing the buffer size will help limit this information, but in the case of a long line of input it may cause some problems. I was hoping to see if anyone knows how to read in a certain amount from the buffer and then split it at the new line indicator (I'm pretty sure its "\n").
Any help/tips would be appreciated! Thanks!