4

我正在尝试使用 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  
4

2 回答 2

1

我想逐行读取文件,而不是一次读取所有文件,因此此代码(1)不起作用。

将数据块读入缓冲区(例如几千字节)。然后逐行处理该缓冲区(通过查找换行符),并在到达缓冲区末尾时从文件中读取更多数据。

我也想写入文件而不是覆盖!

打开文件(系统调用 13)时,将标志 ( $a1) 设置为 9。这对应于“只写与创建和追加”(请参阅​​此 MARS 系统调用参考)。

于 2013-05-20T11:45:00.927 回答
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
于 2013-05-22T18:15:37.130 回答