我正在尝试以文本形式在标准输出中写入一个整数,仅使用 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 mode
和binary 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.
少校:
我找到了答案:
#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/