c - 如何在 C 中使用 write() 函数编写整数?
问题描述
我是 C 的菜鸟,并试图使用write()
函数来显示整数。
这是我的代码:
int n = 7;
write(1, &n, 4);
我想显示7
,但是当我设置n
为大数字时,程序什么也不显示或显示其他奇怪的字符。
我错过了什么?
解决方案
像这样的对象int
在内存中用各种位表示。该write
例程将这些内存位准确地传输到其目的地。
终端并非旨在显示任意内存位。他们不会将这些位解释为一个int
或其他对象,然后显示该解释。通常,我们将字符传输到终端。更具体地说,我们发送代表字符的代码。终端设计用于接收这些代码并显示书写的小图片(字符、字形、表情符号等)。
要让终端显示“7”,我们需要向其发送“7”的代码。字符的通用代码系统是 ASCII(美国信息交换标准代码)。“7”的 ASCII 码是 55。所以,如果你这样做:
char x = 55;
write(1, &x, 1);
如果使用 ASCII,则终端将在其显示屏上绘制“7”。
用于显示值以供人类阅读write
的错误例程也是如此。int
相反,您通常使用printf
,如下所示:
printf("%d", n);
f
inprintf
代表formatted
. _ 它检查表示值的位n
并将表示的值格式化为供人类阅读的字符,然后将这些字符写入标准输出。
If you want to use write
to transmit characters to the terminal, you can use sprintf
to get just the formatting part of printf
without the printing part. For starters, this code will work:
char buffer[80]; // Make space for sprintf to work in.
int LengthUsed = sprintf(buffer, "%d", n); // Format n in decimal.
write(1, buffer, LengthUsed); // Write the characters.
(More sophisticated code would adapt the buffer size to what is needed for the sprintf
.)
推荐阅读
- swift - Apple“延迟照明”在我的 MacBook Pro 2018 和 Vega 20 上都是绿色的
- wpf - 将枚举 System.IO.WatcherChangeTypes 绑定到 ComboBox Itemsource
- python - 根据条件加入列表中的字符串?
- javascript - “对象不支持属性或方法'shift'”在 IE on Focus 到 JQuery Datepicker(仅在更改月/年之后)
- sql - BigQuery 取代了我的大部分 Spark 工作,我错过了什么吗?
- python - 使用 python 模块 pysftp 的安全 ftp 连接
- php - 如何在奏鸣曲管理中自动将图像从父实体存储到子实体
- android - 为什么在 Android Oreo 上关闭屏幕时前台服务停止?
- javascript - 在文件路径/名称中使用 window.open 和主题标签打开文件
- parsing - 如何从柠檬中获取生成的 AST?