Printing into the terminal without printf? Printing into the terminal without printf? unix unix

Printing into the terminal without printf?


You can use write

https://linux.die.net/man/2/write

Example:

#include <unistd.h>#include <string.h>int main(void){    char my_string[] = "Hello, World!\n";    write(STDOUT_FILENO, my_string, strlen(my_string));}

For my uni assignment, I am to write a C program that prints out the content of a file in Linux/Unix into the terminal.

You cannot really "write into the terminal". What you can do is to write to stdout and stderr, and then the terminal will handle it after that.

EDIT:

Well, as KamilCuk mentioned in comments, you can write to the terminal /dev/tty. Here is an example:

#include <fcntl.h>  // open#include <unistd.h> // write#include <string.h> // strlen#include <stdlib.h> // EXIT_FAILUREint 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));}