Mips-打印到文件

时间:2016-04-22 08:44:40

标签: assembly printing io mips system-calls

我想将一些内容(字符串和浮点数)打印到文件中。

这就是我到目前为止所实现的:

.data:
    line_break: .asciiz "\n"
    buffer: .space 1024
.text:
main:
    addi $t0, $zero, -1
    jal open_file                           # open the file to write to
    beq $v0, $t0, create_file               # if return value -1 --> file not available --> create the file
    move $s6, $v0                           # save the file descriptor  
    [...]
    ulw $t0, print_initiaton_message        # save the print_initiaton_message in a temp
    sw $t0, buffer                          # put print_initiaton_message on buffer
    li $v0, 15                              # syscall to write to file
    move $a0, $s6                           # move file descriptor to $a0
    la $a1, buffer                          # target to write from
    li $a2, 1024                            # amount to be written
    syscall                                 # syscall to write in file
    [...]
    s.s $f12, buffer
    li $v0, 15                              # syscall to write to file
    move $a0, $s3                           # move file descriptor to $a0
    la $a1, buffer                          # target to write from
    li $a2, 4                               # amount to be written
    syscall                                 # syscall to write in file
    [...]

基本思想是将必要的信息放入缓冲区,然后进行系统调用。

它似乎有效 - 因为文件已正确创建,之后打开和关闭。其中也有内容,但没有预期的结果:

’®)@

PÀ<@

[...]

在第一个位置,应该有一个字符串,后面跟一个换行符,然后是一个浮点。

现在我的问题: - 如何实现输出的正确格式化? - 如果我的输入超过缓冲区大小,缓冲区大小代表什么以及会发生什么? - 要写的金额是什么意思?

我试图通过几个系统调用引用(即this one),查找示例(以及found thisthat),但主要问题是它们只提供代码和不要覆盖我上面的问题。

2 个答案:

答案 0 :(得分:0)

sw $t0, buffer

这行代码将缓冲区的前32位设置为print_initiaton_message的地址。我不熟悉文件I / O系统调用;但是,我想知道你是否真的想这样做:

li $v0, 15                              # syscall to write to file
move $a0, $s6                           # move file descriptor to $a0
la $a1, print_initiation_message        # target to write from
li $a2, <actual length of initiation message>
syscall                                 # syscall to write in file

答案 1 :(得分:0)

我终于找到了解决方案:

我将数字/字符串的大小设置为打印的1024。因此,我的程序从缓冲区的地址中获取内容,并从堆(或数据)部分另外打印1023个字符。我通过计算字符串中的字符数来修复此问题(因为这是一个用于教育目的的项目,这是可以的)并将大小设置为字符数量;而\ n是一个字节。

我的程序打印的奇怪字符是表示其对应的十六进制值的ASCII符号。我的错误是假设我必须从左到右阅读字符。由于MIPS正在使用Big Endian format,因此必须从右到左读取ASCII字符。创建十六进制转储并计算相应的浮点数会得到正确的结果。

为了避免令人困惑的基于ASCII的输出,需要额外的字符串转换。想法是为每个数字计算其对应的ASCII字符,然后打印结果值。