c - 如何用write在C中输出单个字符?

标签 c function unix

有人可以指导我如何打印单个字母,例如 C 中的“b”,同时仅使用 write 函数(不是 printf)。

我很确定它使用

#include <unistd.h>

你能告诉我写入属性是如何工作的吗?不太懂

int  write(  int  handle,  void  *buffer,  int  nbyte  );

你们中的一些人也可以介绍一些 C 初学者技巧吗?

我正在使用 UNIX。

最佳答案

你已经找到了你的函数,你现在需要的只是给它传递适当的参数:

int handle = open("myfile.bin", O_WRONLY);
//... You need to check the result here
int count = write(handle, "b", 1); // Pass a single character
if (count == 1) {
    printf("Success!");
}

I did indeed want to use stdout. How do I write a version to display the whole alphabet?

您可以为标准输出使用预定义常量。它被称为 STDOUT_FILENO

如果你想写出整个字母表,你可以这样做:

for (char c = 'A' ; c <= 'Z' ; c++) {
    write(STDOUT_FILENO, &c, 1);
}

Demo.

关于c - 如何用write在C中输出单个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31885407/

相关文章:

库达错误 C2054 : expected '(' to follow '__device__'

perl - 为什么 Perl 5 的函数原型(prototype)不好?

linux - 为 "cd ../"设置绑定(bind) key

c - Xilinx Microblaze 中的 Visual C 项目

c - C 函数的平均执行时间不稳定

c - pthread_kill 不会杀死线程 C linux

c - 函数和字符串

matlab - 为什么在 matlab 中 sin(pi) 不精确但 sin(pi/2) 是精确的?

c - 如何在c中正确格式化整数?

macos - 串行端口挂起