【问题标题】:Mips- print to fileMips-打印到文件
【发布时间】:2016-04-22 08:44:39
【问题描述】:

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

这就是我目前实现的:

.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 this,或that),但主要问题是它们只提供代码,并没有涵盖我上面的问题.

【问题讨论】:

    标签: assembly printing io mips system-calls


    【解决方案1】:

    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
    

    【讨论】:

    • 根据 MIPS 指令参考 (available here) sw 将 $t0 的内容保存到指定地址,即缓冲区。我想将 previos 子过程的输出保存到缓冲区,以便我可以打印它。
    • 缓冲区的输出是什么数据类型?如果输出是字符串,则需要将字符串复制到缓冲区中。如果输出是单个整数,则需要先将整数格式化为字符串。
    • 是的,请参阅下面的答案。我找到了解决方案
    【解决方案2】:

    我终于找到了解决办法:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 2012-11-01
      • 2023-02-24
      相关资源
      最近更新 更多