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

落花浮王杯 提交于 2019-11-26 22:03:51

问题


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?


回答1:


It is possible to use rdbuf() to change the destination of std::cin and std::cout inside your program. If you don't do that, it is probably quite safe to assume that cin = 0, cout=1 and clog and cerr both = 2 as the C++ standard states that they are synchronized with C stdin, stdout and stderr and those have per POSIX those file descriptors at startup.




回答2:


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>.



来源:https://stackoverflow.com/questions/5156675/how-to-use-isatty-on-cout-or-can-i-assume-that-cout-file-descriptor-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!