gpt4 book ai didi

c++ - 始终输出到屏幕并允许重定向

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:08:30 25 4
gpt4 key购买 nike

我正在编写一个小型 CLI 应用程序,我希望允许用户重定向到一个文件,而标准 cout 语句转到 output.txt 文件我希望进度始终显示在屏幕上。

./myApp > output.txt
10% complete
...
90% complete
Completed

这可能吗?我该怎么做?

提前致谢!

最佳答案

即使 stdinstdout 都被重定向,这仍然有效:

spectras@etherbee:~$ ./term
hello terminal!
spectras@etherbee:~$ ./term >/dev/null 2>&1
hello terminal!

想法是直接打开进程的控制终端,绕过任何重定向,像这样:

#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
int fd = open("/dev/tty", O_WRONLY);
if (fd < 0 && errno != ENODEV) {
/* something went wrong */
return 1;
}
int hasTTY = (fd >= 0);

if (hasTTY) {
write(fd, "hello terminal!\n", 16);
}
return 0;
}

来自 man 4 tty:

The file /dev/tty is a character file with major number 5 and minor number 0, usually of mode 0666 and owner.group root.tty. It is a synonym for the controlling terminal of a process, if any.

如果您使用的是 C++,您可能希望将文件描述符包装到一个自定义的 streambuf 中,这样您就可以在其上使用常规的流 API。或者,C++ 库的某些实现为此目的提供了扩展。参见 here .
或者,如果您不关心可靠地获取错误代码,您可以只使用 std::ofstream terminal("/dev/tty")

如果您这样做,作为设计考虑,提供一个安静的选项让用户关闭写入终端也是一个好主意。

关于c++ - 始终输出到屏幕并允许重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45766107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com