2013-02-15 1189 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')。