将控制台输出写入.txt并在控制台上显示

Write console output to .txt AND show it on console

本文关键字:控制台 显示 输出 txt      更新时间:2023-10-16

我最近发现您可以使用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