c - 在没有 printf 的情况下打印到终端?
问题描述
我想编写一个 C 程序,将文件的内容打印到终端中。
但是,我们不允许使用该<stdio.h>
库,因此printf
无法使用类似的功能。
将内容打印到终端的替代方法是什么?
我正在做一些搜索,但我找不到直接的答案,因为大多数人只是使用printf
.
解决方案
您可以使用write
https://linux.die.net/man/2/write
例子:
#include <unistd.h>
#include <string.h>
int main(void)
{
char my_string[] = "Hello, World!\n";
write(STDOUT_FILENO, my_string, strlen(my_string));
}
对于我的 uni 任务,我要编写一个 C 程序,将 Linux/Unix 中文件的内容打印到终端中。
您不能真正“写入终端”。您可以做的是写入stdout和stderr,然后终端将处理它。
编辑:
好吧,正如 KamilCuk 在评论中提到的,你可以写信给终端/dev/tty
。这是一个例子:
#include <fcntl.h> // open
#include <unistd.h> // write
#include <string.h> // strlen
#include <stdlib.h> // EXIT_FAILURE
int main(void)
{
int fd = open("/dev/tty", O_WRONLY);
if(fd == -1) {
char error_msg[] = "Error opening tty";
write(STDERR_FILENO, error_msg, strlen(error_msg));
exit(EXIT_FAILURE);
}
char my_string[] = "Hello, World!\n";
write(fd, my_string, strlen(my_string));
}
推荐阅读
- django - 传单分组图层未显示在地图上
- angular - 有条件地展示一个孩子或另一个孩子
- c# - Entity Framework Core / SQLite:加入“扁平化”结果后的 GroupJoin
- c++ - 有没有办法定义一个快捷方式 elif 来替换 else if?
- javascript - 如何在JS中删除数组中的向量
- java - 互联网连接检查行为怪异
- c# - 带有 32 位可执行文件的 C# 问题
- c# - bot 框架/LUIS - 服务在多台机器上运行时会话上下文丢失
- c# - 默认情况下,类不表现为内部
- android - 找不到引用的类 kotlin.KotlinPackage