2

I want to write a C program that prints out the content of a file in into the terminal.

However, we are not allowed to use the <stdio.h> library, so functions like printf aren't available.

What are the alternative ways to print things into the terminal?

I was doing some searching but I couldn't find a direct answer as most people simply use printf.

EsmaeelE
  • 2,331
  • 6
  • 22
  • 31
  • Also this should help [How to invoke a system cal -via sysenter in inline assembly](https://stackoverflow.com/questions/9506353/how-to-invoke-a-system-call-via-sysenter-in-inline-assembly) – Agnius Vasiliauskas Aug 28 '20 at 08:40

1 Answers1

7

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_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));
}
klutt
  • 30,332
  • 17
  • 55
  • 95
  • 1
    From what i understand, this writes it into the file. does it print it out to the terminal as well? – secondary account Aug 28 '20 at 07:33
  • 2
    @secondaryaccount It writes it to standard output – klutt Aug 28 '20 at 07:36
  • 3
    Nitpicking: `You cannot really "write into the terminal"` Well, you can write to `/dev/tty`, and `/dev/tty` is the "controlling terminal", so writing to `/dev/tty` would be like writing into a terminal – KamilCuk Aug 28 '20 at 08:29