首页 > 解决方案 > 在没有 printf 的情况下打印到终端?

问题描述

我想编写一个 C 程序,将文件的内容打印到终端中。

但是,我们不允许使用该<stdio.h>库,因此printf无法使用类似的功能。

将内容打印到终端的替代方法是什么?

我正在做一些搜索,但我找不到直接的答案,因为大多数人只是使用printf.

标签: clinuxunixoutputsystem-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 在评论中提到的,你可以写信给终端/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));
}

推荐阅读