2013-02-15 1179 views
1

我試圖用MIPS彙編語言編寫簡單的程序。我想要做的是從鍵盤讀取多個字符並將其保存到文件。我使用13個操作碼創建文件並使用15個操作碼保存字符。我不明白:如何動態分配字符數以寫入$ a2中的15個操作碼(第37行,現在硬編碼)。此外,我無法弄清楚如何打印寫入我的文件的字符數($ v0在寫入文件後第49行包含此值)。學習MIPS彙編:讀取文本並寫入文件

現在的程序是拋出錯誤: 49行:在0x00400078運行時異常:地址超出範圍0x0000002c

這裏是我的代碼:

.data 

handle_text: 
    .space 100 # buffor of 100 characters, bits, bytes? 

out_file: 
    .asciiz "file_out.txt" # out file 

asklabel: 
    .asciiz "\Please enter string to save\n" 

countlabel: 
    .asciiz "\Characters typed:\n" 

.text 
main: 
    la $a0, asklabel # text to print 
    li $v0, 4 # opcode 
    syscall 

    la $a0, handle_text # Where to put text 
    la $a1, handle_text # Number of characters to write 
    li $v0, 8 # opcode 
    syscall 

    li $v0, 13  # system call for open file 
    la $a0, out_file  # output file name 
    li $a1, 1  # Open for writing (flags are 0: read, 1: write) 
    li $a2, 0  # mode is ignored 
    syscall   # open a file (file descriptor returned in $v0) 
    move $s6, $v0  # save the file descriptor 

    move $a0, $s6 # file handle 
    la $a1, handle_text # text to print 
#line 37 
    li $a2, 44 # TEXT LENGTH 
    li $v0, 15 # opcode 
    syscall 

    move $t1, $v0 # move v0 to t1 so v0 won't be overwritten 

    la $a0, countlabel # show text 
    li $v0, 4 # op code 
    syscall 

    move $a0, $t1 # place characters amount in $a0 
    li $v0, 4 # opcode 
    syscall 
# ERROR. Maybe it's becouse string should be null terminated? 

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

    li $v0, 10 # close app 
    syscall 
+0

[學習x86彙編。從鍵盤讀取並保存到文件](http://stackoverflow.com/questions/14885635/learning-x86-assembly-read-from-keyboard-and-save-to-file) – 2013-02-15 23:15:24

+4

這是MIPS,不是x86彙編.. 。 – 2013-02-16 06:59:17

+0

系統調用號碼不是[「opcodes」](https://en.wikipedia.org/wiki/Opcode)。 MIPS操作碼是指示它是哪個指令的指令詞的一部分。例如[高位'0010 00'表示'addi'](http://www.mrc.uidaho.edu/mrc/people/jff/digital/MIPSir.html),其餘部分指定操作數。 – 2017-10-21 03:08:52

回答

1

的所有

# buffor of 100 characters, bits, bytes? 

第一它們是字節,而不是位。 此外,串

la $a1, handle_text  

在第21行是完全錯誤的,因爲你需要加載一些,而不是一個地址。 可以使用例如

.data 
legnth: .word 100 

[...] 
lw $a1, length 

而且,得到記住,你可以有效地只讀99個字符,導致最後必須是一個'/0'。 在第37行,你仍然可以使用

lw $a2, lenght 

,而不是硬編碼的44

關於本

# ERROR. Maybe it's because string should be null terminated? 

不,這是因爲你想打印一個字符串,而$ T1 = $ v0是一個整數。要打印讀取的字符數,您必須調用系統調用1(不是4)。

要回答你的問題,將普通數字傳遞給參數並不是那麼簡單,因爲你必須以某種方式設置最大數量。例如,以這種方式,即使您輸入10個字符,輸出始終爲100。要解決這個最簡單的方法是用一個「循環」,像

li $t0, -1 
loop: 
    addi $t0, $t0, 1 
    lw $t1, handle_text($t0) 
    bnez $t1, loop 
addi $t0, $t0, -1 

在代碼的結尾,$ T0包含的字符的確切人數(不包括'\0''\n')。