简体   繁体   English

如何在cout上使用isatty(),还是可以假设cout ==文件描述符1?

[英]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 / O重定向来交互使用或在脚本中使用。 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. 我正在使用cincout进行I / O,如果输出是console,我想在末尾写一个额外的EOL,以便用户提示符将从下一行开始。 Within scripts this would be harmful. 在脚本中这将是有害的。

Can I assume cin == 0, cout == 1 ? 我可以假设cin == 0, cout == 1吗? I understand that there is no clean way to get the file descriptor of a stream. 我知道没有干净的方法来获取流的文件描述符。 Or is it? 还是?

If using Linux (and probably other unixes, but definitely not Windows) you could try isatty . 如果使用Linux(可能还有其他的Unix,但肯定不是Windows),则可以尝试isatty

There's no direct way of extracting the file descriptor from the C++ stream. 没有直接方法从C ++流中提取文件描述符。 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)) . 但是,由于在C ++程序中,cout和stdout存在并且同时工作(默认情况下,C ++提供stdio和iostream方法之间的同步),所以我认为最好的选择是做isatty(fileno(stdout))

Make sure you #include <unistd.h> . 确保您#include <unistd.h>

It is possible to use rdbuf() to change the destination of std::cin and std::cout inside your program. 可以使用rdbuf()在程序中更改std :: cin和std :: cout的目的地。 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. 如果您不这样做,则假定cin = 0,cout = 1且clog和cerr都等于2可能是非常安全的,因为C ++标准规定它们与C stdin,stdout和stderr同步,并且每个都具有在启动时POSIX这些文件描述符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM