在没有 printf 的情况下打印到终端?

sec*_*unt 1 c unix linux system-calls output

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

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

将东西打印到终端的替代方法是什么?

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

klu*_*utt 6

您可以使用 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));
}
Run Code Online (Sandbox Code Playgroud)

对于我的 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));
}
Run Code Online (Sandbox Code Playgroud)

  • 吹毛求疵:`你不能真正“写入终端”`好吧,你可以写入`/dev/tty`,而`/dev/tty`是“控制终端”,所以写入`/dev/tty`会就像写入终端一样 (3认同)
  • @secondaryaccount 将其写入标准输出 (2认同)