将控制台输出写入.txt并在控制台上显示
Write console output to .txt AND show it on console
我最近发现您可以使用Visual Studio将C++程序的控制台输出保存到文本文件中(在项目属性的命令参数中添加">输出.txt"(。
问题是我希望输出同时显示在我创建的输出文件和命令控制台中,以便于调试(一旦将输出保存到文件,它就不再显示在控制台上(。是否有任何选项可以在Visual Studio中启用这两个功能或类似功能?
您可以使用自定义流在输出时将数据发送到多个目标。通过创建合适的流缓冲区,可以轻松创建这些缓冲区。例如:
#include <fstream>
#include <iostream>
#include <ostream>
#include <streambuf>
class teebuf
: public std::streambuf {
std::streambuf* d_sbuf1;
std::streambuf* d_sbuf2;
public:
teebuf(std::streambuf* sbuf1, std::streambuf* sbuf2)
: d_sbuf1(sbuf1), d_sbuf2(sbuf2) {
}
int overflow(int c) {
if (c != std::char_traits<char>::eof()) {
this->d_sbuf1->sputc(c);
this->d_sbuf2->sputc(c);
}
return std::char_traits<char>::not_eof(c);
}
};
int main() {
std::ofstream out("foo.txt");
teebuf tb{out.rdbuf(), std::cout.rdbuf()};
std::streambuf* coutbuf = std::cout.rdbuf(&tb);
std::cout << "hello world! (to both the console and the file)n";
std::cout.rdbuf(coutbuf); // needs to be replaced as it gets used to flush
}
当然,这是一种侵入性的方法,需要更改源。我不使用 MSVC++,也无法评论是否有将标准输出保存到文件的方法。
您可以使用命令 tee 来实现此目的
假设你有一个名为myExe的可执行文件(是否用C++实现并不重要(,你可以执行以下操作:
./myExec | tee output.txt
如果要在 Visual Studio 中实现此目的,请使用下列方法之一更改> output.txt
1. 在 Linux 上工作:
| tee output.txt
2. 在窗口上工作:
> output.txt && type output.txt
相关文章:
- 控制台输出在 Qt5 中未正确显示
- Visual Studio 2017 停止工作,并在打开后显示许多控制台窗口
- 为什么调试时没有显示控制台窗口
- 将控制台输出写入.txt并在控制台上显示
- 当被一个输入分开时,有两个控制台输出同时显示
- 如何在控制台应用程序中添加滚动功能以显示更大的输入
- 在任何 Windows 版本上全屏显示控制台
- C++:显示控制台窗口的输出
- C++:如何在控制台窗口中显示结果
- 控制台输出显示ASCII值,而不是数字的预期数字
- C++/CLI 项目如何在控制台窗口中显示消息
- Linux C LIBEV官方示例显示了冗余控制台行为
- QProcess::startDetached() 不显示控制台窗口
- 如何在IDE中而不是在命令提示符中显示Visual Studio控制台应用程序输出
- 如何使用我的 if-else 语句根据用户权重的输入执行特定操作,然后将其显示到控制台?
- 在后台控制台窗口中显示光标
- 向控制台显示随机数
- 用于跨平台的C++控制台显示
- 使用_CrtDumpMemoryLeaks向控制台显示数据
- 如何在打开外部应用程序时阻止控制台显示