我能够(部分)成功地读取 MIP 中的文件。下面是我当前的代码。在 QtSpim 中,当我运行它时,我得到一个指向 $a1 中文件的指针,但文件的最后几个字符重复了两次。重复的字符数根据文件而变化。从我所见,它似乎与文件中的换行符数量相关,除非换行符位于文件的最末尾(也就是说,如果有 5 个换行符,则文件的最后 5 个字符将在读入的文件末尾出现重复),尽管我不明白为什么这是真的。 (仅供引用,此代码几乎是从 here 中逐字复制的,只是它是读取而不是写入)
.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
最佳答案
您无法知道此代码是否重复了最后一行。您提供的链接在文件读取的结果列中清楚地表明 $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
关于assembly - 在MIPS中读取文件时,它读取最后一行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23146234/