【发布时间】:2020-12-17 02:52:58
【问题描述】:
我想编写一个 C 程序,将文件的内容打印到终端中。
但是,我们不允许使用 <stdio.h> 库,所以像 printf 这样的函数不可用。
将内容打印到终端的替代方法是什么?
我正在做一些搜索,但我找不到直接的答案,因为大多数人只是使用printf。
【问题讨论】:
标签: c linux unix output system-calls
我想编写一个 C 程序,将文件的内容打印到终端中。
但是,我们不允许使用 <stdio.h> 库,所以像 printf 这样的函数不可用。
将内容打印到终端的替代方法是什么?
我正在做一些搜索,但我找不到直接的答案,因为大多数人只是使用printf。
【问题讨论】:
标签: c linux unix output system-calls
你可以使用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 在 cmets 中提到的,你可以写信到终端 /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));
}
【讨论】:
You cannot really "write into the terminal" 好吧,你可以写信给/dev/tty,/dev/tty 是“控制终端”,所以写信给/dev/tty 就像写终端一样