Writing to stdout except for output redirection C

cstdouttty

I have to make a simple app for school.

I have to write arguments one per line on the terminal, and return on stdout the user choices.

For example, I write cat my_app main.c main.h, if the user choose main.c, then I return main.c to cat. The problem is that if I write the menu on the standard output (aka STDOUT_FILENO), I return it to cat. I could write my menu on STDERR, but it's a little ugly.

I don't really know how to use devices/files like /dev/tty* or /dev/pty*, but I feel I could use them to write something on the terminal without having to write it on STDOUT or STDERR.

Basically, I want to open a new output, which would be shown by the terminal (STDOUT, STDERR, MYOUT).

I don't know if I explained it correctly.

Best Answer

To build an interactive application you can open /dev/tty, it will return a file descriptor to the controlling terminal:

int ttyfd = open("/dev/tty", O_RDWR);

You can use it instead of STDIN_FILENO or STDOUT_FILENO (those could be redirected to something different than the terminal when the program is started).


Here is some example:

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main() {
  int ttyfd = open("/dev/tty", O_RDWR);
  printf("fd: %d\n", ttyfd);
  write(ttyfd, "hello tty!\n", 11);
  return 0;
}

When invoked with ./test >out, it should print the hello message on the terminal and something like fd: 3 in the out file.

Related Question