When reading a file in MIPS, it reads the last line twice

I was able to (partially) successfully read the file into MIP. Below is my current code. In QtSpim, when I run it, I get a file pointer at $ a1, but the last few characters of the file are repeated twice. The number of repeated characters varies depending on the file. From what I've seen, it seems to be related to the number of newlines in the file, unless newlines are at the very end of the file (which means if there were 5 newlines, the last 5 characters of the file would be duplicated at the end file read), although I see no reason why this should be true. (FYI, this code is copied almost verbatim from here , except that it reads instead of writes)

.data
fin: .asciiz "c:/input.txt"
fBuffer: .space 1024
.text
main:
    jal  openFile
    jr   $ra

#returns: pointer to file text in $a1
openFile:
    li   $v0, 13       # system call for open file 
    la   $a0, fin  #fin is the file name
    li   $a1, 0    # 0 means 'read'
    li   $a2, 0
    syscall            # open file
    move $s6, $v0      # save the file descriptor

    #read from file
    li   $v0, 14       # system call for read from file
    move $a0, $s6      # file descriptor 
    la   $a1, fBuffer   
    li   $a2, 1024     # hardcoded buffer length
    syscall            # read from file

    # Close the file 
    li   $v0, 16       # system call for close file
    move $a0, $s6      # file descriptor to close
    syscall            # close file
    jr $ra

      

+1


source to share


1 answer


You may not know that the last line was repeated with this code. The link you gave clearly says in the Result column for reading the file, which $v0

contains the number of bytes read. But your code immediately compresses $v0

to close the file.

If you change your code to only print characters that are actually readable, the appearance of duplicate information should disappear.



If you are using a print string syscall

, just add one byte to the buffer (to prevent overflow) and then write a null terminator after the characters have been read. Something like:

syscall            # (your code) read from file 
la $a0, fBuffer    # load 32-bit buffer address
add $a0, $a0, $v0  # calculate address of byte after file data 
sb $zero, 0($a0)   # set that byte to zero

      

+1


source







All Articles