4
votes

I'm trying to do some access on file using mips instruction.
I want to read file line by line not all of the file at a time so this code(1) does not work.

Also I want to write to the file and not overwrite!
Can any one help me?

Code:

Open a file for writing

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 

Read from file

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  

Close the file

li   $v0, 16       # system call for close file  
move $a0, $s6      # file descriptor to close  
syscall            # close file  
2

2 Answers

1
votes

I want to read file line by line not all of the file at a time so this code(1) does not work.

Read chunks of data into a buffer (e.g. a few kilobytes). Then process that buffer line-by-line (by looking for linefeed characters), and read more data from the file when you've reached the end of the buffer.

Also I want to write to the file and not overwrite!

Set the flags ($a1) to 9 when opening the file (syscall 13). This corresponds to "write-only with create and append" (see this MARS syscall reference).

0
votes

it's work thx alot :)

.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