Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use isatty() on cout, or can I assume that cout == file descriptor 1?

Well, the subject says it all, basically.

I have a command-line utility that may be used interactively or in scripts, using pipes or i/o redirection. I am using cin and cout for i/o, and I want to write an extra EOL at the end if the output is console, so that user prompt will start from the next line. Within scripts this would be harmful.

Can I assume cin == 0, cout == 1? I understand that there is no clean way to get the file descriptor of a stream. Or is it?

like image 366
davka Avatar asked Mar 01 '11 15:03

davka


1 Answers

If using Linux (and probably other unixes, but definitely not Windows) you could try isatty.

There's no direct way of extracting the file descriptor from the C++ stream. However, since in a C++ program both cout as well as stdout exist and work at the same time (C++ by default provides synchronisation between stdio and iostream methods), your best bet in my opinion is to do a isatty(fileno(stdout)).

Make sure you #include <unistd.h>.

like image 163
Dan Avatar answered Sep 22 '22 18:09

Dan