Question

I am using the MARS program to write some MIPS assembly code and the program I am writing needs to take in an input file and then iterate through it to change some numbers. I have all of the body of the code written but I am not sure how to actual take in a file. I have the following code that reads in the input and stores the address:

.data 0x0
magicNum:       .asciiz "P2"  #magic number
zero:   .word 0
newLine:        .asciiz "\n"  #new line character

.text 0x3000

main:
        ori $v0, $0, 8          #8 is syscall to read string
        ori $a0, $0, 100        #stores address of input buffer
        ori $a1, $0, 3          #max character to read in
        syscall

#the rest of the code is down here

but where do I actually put the file on Windows to have it taken in?

Was it helpful?

Solution

You have to use syscall 13 to open a file, and then use syscall 14 to read from it and store its contents into a buffer.

Here's a snippet to get you started, just fill in the gaps with your code:

.data
filename: .asciiz "file.txt"
buffer: .space 1024

.text

    la $a0, filename
    li $a1, 0       # readonly
    li $a2, 0
    li $v0, 13
    syscall         # open file
    bltz $v0, file_error
    move $a0, $v0    
    la $a1, buffer
    li $a2, 1024
read_file:
    li $v0, 14
    syscall
    beqz $v0, read_done
    bltz $v0, read_error
    addu $a1, $a1, $v0   # adjust buffer pointer
    subu $a2, $a2, $v0
    bnez $a2, read_file   # If buffer not full and not EOF, continue reading
read_done:
   # File copied to buffer
   # Your code goes here

file_error:
   # Code to take action if file errors occur (e.g. file not found)

read_error: 
   # Code to take action if read errors occur

If you are using MARS the file should be located in the current directory (the place where you started MARS).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top