2

我能够(部分)成功读取 MIP 中的文件。以下是我当前的代码。在 QtSpim 中,当我运行它时,我在 $a1 中得到一个指向文件的指针,但文件的最后几个字符重复了两次。重复的字符数因文件而异。从我所见,它似乎与文件中换行符的数量有关,除非换行符位于文件的最后(意思是,如果有 5 个换行符,则文件的最后 5 个字符在读入的文件末尾会出现重复),尽管我看不出有任何理由说明这应该是真的。(仅供参考,这段代码几乎是从这里逐字复制的,只是它是读取而不是写入)

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

#returns: pointer to file's 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
4

1 回答 1

2

您无法知道此代码重复了最后一行。您提供的链接在文件读取的结果列中清楚地说明了$v0包含读取的字节数。但是您的代码会立即$v0关闭文件。

如果您将代码更改为仅打印实际读取的字符,那么重复信息的出现应该会消失。

如果您使用的是打印字符串syscall,则只需向缓冲区添加一个字节(以防止溢出),然后在读取字符后写入一个空终止符。就像是:

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
于 2014-04-18T02:39:32.907 回答