将std::cout的副本重定向到文件
Redirect the copy of std::cout to the file
我需要重定向 std::cout的副本到文件。也就是说,我需要在控制台和文件中看到输出。如果我使用这个:
// redirecting cout's output
#include <iostream>
#include <fstream>
using namespace std;
int main () {
streambuf *psbuf, *backup;
ofstream filestr;
filestr.open ("c:\temp\test.txt");
backup = cout.rdbuf(); // back up cout's streambuf
psbuf = filestr.rdbuf(); // get file's streambuf
cout.rdbuf(psbuf); // assign streambuf to cout
cout << "This is written to the file";
cout.rdbuf(backup); // restore cout's original streambuf
filestr.close();
return 0;
}
然后我将字符串写入文件,但我在控制台中看到什么都没有。我该怎么做呢?
最简单的方法就是创建一个输出流类:
#include <iostream>
#include <fstream>
class my_ostream
{
public:
my_ostream() : my_fstream("some_file.txt") {}; // check if opening file succeeded!!
// for regular output of variables and stuff
template<typename T> my_ostream& operator<<(const T& something)
{
std::cout << something;
my_fstream << something;
return *this;
}
// for manipulators like std::endl
typedef std::ostream& (*stream_function)(std::ostream&);
my_ostream& operator<<(stream_function func)
{
func(std::cout);
func(my_fstream);
return *this;
}
private:
std::ofstream my_fstream;
};
请参阅此ideone链接以查看此代码的实际操作:http://ideone.com/T5Cy1M我目前不能检查文件输出是否正确,虽然它不应该是一个问题。
您也可以使用boost::iostreams::tee_device
。参见c++ "hello world"Boost tee示例程序为示例。
您的代码不起作用,因为是streambuf
决定写入流的输出在哪里结束,而不是流本身。
c++没有任何支持将输出定向到多个目标的流或流bufs,但您可以自己编写一个。
相关文章:
- 如何将stdout重定向到stderr
- 编写时C++中的输入重定向问题
- 获取通过重定向传入的输入文件的名称?
- Windows C++重定向库
- 写入文件 a.txt,而终端重定向到文件 b.txt
- 使用 dup2() 进行输入重定向
- 将 clangd stderr 重定向到文件而不是控制台
- 如何在C++中获取重定向网页的URL
- 将标准输出重定向到ostream
- 如何撤消此代码上的 cin 重定向?
- 使用重定向标准处理子进程中的 kbhit
- 是否可以将子进程的 stdout 重定向到父进程中的另一个文件?
- 重定向输入和输出时如何处理主文件I/O?
- 如何将HTTPS流量重定向到本地主机:443上的代理?
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- 尝试在 Windows 上重定向 stdout 和 stderr——_fileno(stdout) 返回 -2
- 可以将Boost消息队列文件重定向到用户指定的位置
- 在程序执行期间从标准输出重定向到自定义流
- 如何使用PHP将上传到本地主机的一个html文件重定向到磁盘上的另一个html文档
- 将std::cout的副本重定向到文件