.globl read_matrix .text # ============================================================================== # FUNCTION: Allocates memory and reads in a binary file as a matrix of integers # # FILE FORMAT: # The first 8 bytes are two 4 byte ints representing the # of rows and columns # in the matrix. Every 4 bytes afterwards is an element of the matrix in # row-major order. # Arguments: # a0 (char*) is the pointer to string representing the filename # a1 (int*) is a pointer to an integer, we will set it to the number of rows # a2 (int*) is a pointer to an integer, we will set it to the number of columns # Returns: # a0 (int*) is the pointer to the matrix in memory # Exceptions: # - If malloc returns an error, # this function terminates the program with error code 88. # - If you receive an fopen error or eof, # this function terminates the program with error code 90. # - If you receive an fread error or eof, # this function terminates the program with error code 91. # - If you receive an fclose error or eof, # this function terminates the program with error code 92. # ============================================================================== read_matrix: #open the filename addi sp,sp,-28 sw ra, 0(sp) sw s0, 4(sp) sw s1, 8(sp) sw s2, 12(sp) sw s3, 16(sp) sw s4, 20(sp) sw s5, 24(sp) ##Initialize variables a0,a1,a2 mv s0,a0 mv s1,a1 mv s2,a2 mv s3,x0 #bytes to store mv s4,x0 #file descriptor mv s5,x0 open_file: #Give read instructions for fopen mv a2,x0 #read permission to 0 mv a1,s0 #filename of the file we are opening #Opens the file jal ra, fopen #if a0 is -1 mv t0,x0 li t1,1 sub t0,t0,t1 beq a0,t0,error #a0 is now the file descriptor, if -1 account for an error mv s4,a0 #set file descriptor read_file: #this is for fread #Prepare malloc #Number of bytes to read 4*(2+m*n) li t0,1 lw t1, 0(s1) #rows lw t2, 0(s2) #columns mul t0,t1,t2 addi t0,t0,2 li t3,4 mul t0,t0,t3 mv s3, t0 mv a0, s3 #size of buffer jal ra, malloc mv a1, s4 #file descriptor mv a2, a0 #pointer to buffer that we previously malloced mv a3,s3 #number of bytes to read jal ra, fread #call fread function #set return value to the address of a2 mv s5,a2 mv a0,s5 lw ra, 0(sp) lw s0, 4(sp) lw s1, 8(sp) lw s2, 12(sp) lw s3, 16(sp) lw s4, 20(sp) lw s5, 24(sp) addi sp,sp,28 #update stack poitner ret error: li a1, 79 jal exit2