c - 仅使用 write() 以文本形式将整数写入 stdout

标签 c int system-calls

我正在尝试以文本形式在标准输出中写入一个整数,仅使用 write() 函数以及可能的 while/if。

我想以文本形式写出整数,以便人类可读,但实际上它是以二进制形式写出的:

这是我尝试过的:

main.c:

#include "my_put_nbr.h"
int main()
{
    my_put_nbr(43);
    return 0;
}

my_put_char.c:

#include <unistd.h>
int my_put_nbr(int nb)
{
        write(1, &nb, sizeof(nb));
        return 0;
}

那么如何仅用 write(或 putchar)和条件以文本形式写出整数?

PS:我不能使用其他库,所以我不能使用 printf 或其他任何东西!

我的github:link

text modebinary mode在计算机科学中很常见,但这里提醒那些不明白我的意思的人 text form :

On a UNIX system, when an application reads from a file it gets exactly what's in the file on disk and the converse is true for writing. The situation is different in the DOS/Windows world where a file can be opened in one of two modes, binary or text. In the binary mode the system behaves exactly as in UNIX. However on writing in text mode, a NL (\n, ^J) is transformed into the sequence CR (\r, ^M) NL.

引自Cygwin.com

<小时/>

少校:

我找到了答案:

#include "my_putchar.h"
/* 0x2D = '-'
 * 0x0 = NUL */
int my_put_nbr(int n)
{
        if (n < 0)
        {
                my_putchar(0x2D);
                n = -n;
        }

        if (n > 9)
        {
                my_put_nbr(n/10);
        }

        my_putchar((n%10) + '0');

        return 0;
}

最佳答案

write是写入,不过是写入不可见字符。 您可以通过以下方式查看:

./myprogram | od -tx1

在打印之前,您需要将 n 中的数字(整数值 23)转换为字符串“23”。

一种方法:

  char buffer[16];
  snprintf(buffer, sizeof(buffer), "%d", n);
  write(1, buffer, strlen(buffer));

关于c - 仅使用 write() 以文本形式将整数写入 stdout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34661426/

相关文章:

c - 如何获取 Windows session 名称?

c - lint 错误 18 "Symbol ' CsiNetInit(void)' 重新声明(精度)与第 21 行冲突

php - 为什么 1024 * 1024 * 1024 * 1024 * 1024 返回 float ?

java - 在 Reader 中打开 PDF 并等待其退出

c - fork 调用子进程和父进程后,值会有什么不同?

python - 如果另一个实例已经在运行,如何杀死 python 脚本及其子脚本

c - 将 uint8_t 数组参数传递给除 uint32_t 之外的子例程(从 uint8_t 数组转换为 uint32_t 数组)

c - 从使用 atexit() 注册的函数内部获取退出状态

java - 生成一个大于或小于前一个随机数的随机数

c++ - 如何将 C++ 字符串转换为 int?