我正在尝试使用mips指令对文件进行一些访问 我想逐行读取文件,而不是一次读取所有文件,因此这段代码(1)不起作用。
此外,我想写入文件而不是覆盖!
任何人都可以帮助我吗?
代码:
打开文件进行编写
li $v0, 13 # system call for open file
la $a0, file # board file name
li $a1, 0 # Open for reading
li $a2, 0
syscall # open a file (file descriptor returned in $v0)
move $s6, $v0 # save the file descriptor
从文件中读取
li $v0, 14 # system call for read from file
move $a0, $s6 # file descriptor
la $a1, buffer # address of buffer to which to read
li $a2, 40 # hardcoded buffer length
syscall # read from file
关闭文件
li $v0, 16 # system call for close file
move $a0, $s6 # file descriptor to close
syscall # close file
答案 0 :(得分:1)
我想逐行读取文件,而不是一次读取所有文件,因此此代码(1)不起作用。
将数据块读入缓冲区(例如几千字节)。然后逐行处理缓冲区(通过查找换行符),并在到达缓冲区末尾时从文件中读取更多数据。
此外,我想写入文件而不是覆盖!
打开文件时将标志($a1
)设置为9(系统调用13)。这对应于“只写与创建和附加”(参见this MARS syscall reference)。
答案 1 :(得分:0)
它的工作很多很多:)
.data
fin: .asciiz "file.txt" # filename for input
buffer: .space 128
buffer1: .asciiz "\n"
val : .space 128
.text
################################################ fileRead:
# Open file for reading
li $v0, 13 # system call for open file
la $a0, fin # input file name
li $a1, 0 # flag for reading
li $a2, 0 # mode is ignored
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 buffer from which to read
li $a2, 6 # hardcoded buffer length
syscall # read from file
li $v0, 4 #
la $a0, buffer # buffer contains the values
syscall # print int
lb $t1 , buffer
# reading from file just opened
li $v0, 14 # system call for reading from file
move $a0, $s0 # file descriptor
la $a1, buffer # address of buffer from which to read
li $a2, 6 # hardcoded buffer length
syscall # read from file
li $v0, 4 #
la $a0, buffer # buffer contains the values
syscall # print int
## sh $t5 , val($0) #sw $t5, theArray($t0)
# Close the file
li $v0, 16 # system call for close file
move $a0, $s6 # file descriptor to close
syscall # close file