C++에서 stdout의 출력을 콘솔과 파일로 미러링하는 스마트 방법이 있습니까? 나는 this question처럼 그것을 할 수있는 방법이 있기를 바라고 있습니다.콘솔 콘솔 출력을 C++ 파일로
편집 :
C++에서 stdout의 출력을 콘솔과 파일로 미러링하는 스마트 방법이 있습니까? 나는 this question처럼 그것을 할 수있는 방법이 있기를 바라고 있습니다.콘솔 콘솔 출력을 C++ 파일로
편집 :
당신은이 Tee Device Boost.Iostreams에서 제공 시도해 볼 수도 있습니다 .. : (아무 부스트 예) 그냥 표준 라이브러리를 사용하여이 작업을 수행 할 수있을 좋을 것이다.
A 티 장치는 출력을 여러 스트림으로 보냅니다. 내가 아는 한, write
호출에서 이론적으로는 무한 출력 장치에 도달하도록 연결할 수 있습니다.
This answer은 원하는대로 정확하게 수행하는 방법에 대한 예를 보여줍니다.
tee 명령으로 파이프되도록 프로그램을 시작하십시오.
std::streambuf
을 확장하고 std::ofstream
멤버가있는 클래스를 만들어이 작업을 수행 할 수 있습니다. std::streambuf::overflow
및 std::streambuf::sync
멤버 함수를 재정 의하여 모든 설정이 완료됩니다.
아래 코드의 대부분은 here에서 비롯됩니다. 파일 미러링을 위해 추가 한 항목 ("ADDED :")이 지적되었습니다. 이 작업은 지나치게 복잡 할 수 있으며 작업을 단순화하기 위해 완전히 숨길 수는 없지만 작동합니다 (이 코드는 std::streambuf*
을 사용하는 대신 보너스가 있습니다. . std::cout
에 기록 외부 라이브러리)
#ifndef MYSTREAMBUF_H
#define MYSTREAMBUF_H
template <typename charT, typename traits = std::char_traits<charT> >
class mystreambuf : public std::basic_streambuf<charT, traits>
{
public:
// The size of the input and output buffers.
static const size_t BUFF_SIZE = 1024;
typedef traits traits_type;
typedef typename traits_type::int_type int_type;
typedef typename traits_type::pos_type pos_type;
typedef typename traits_type::off_type off_type;
// You can use any method that you want, but here, we'll just take in a raw streambuf as a
// slave I/O object. xor_char is what each character is xored with before output.
explicit mystreambuf(std::streambuf* buf)
: out_buf_(new charT[BUFF_SIZE])
{
// ADDED: store the original cout stream and open our output file
this->original_cout = buf;
outfile.open("test.txt");
// Initialize the put pointer. Overflow won't get called until this buffer is filled up,
// so we need to use valid pointers.
this->setp(out_buf_, out_buf_ + BUFF_SIZE - 1);
}
// It's a good idea to release any resources when done using them.
~mystreambuf() {
delete [] out_buf_;
// ADDED: restore cout, close file
std::cout.rdbuf(original_cout);
outfile.flush();
outfile.close();
}
protected:
// This is called when there are too many characters in the buffer (thus, a write needs to be performed).
virtual int_type overflow(int_type c);
// This is called when the buffer needs to be flushed.
virtual int_type sync();
private:
// Output buffer
charT* out_buf_;
// ADDED: tracking the original std::cout stream & the file stream to open
std::streambuf* original_cout;
std::ofstream outfile;
};
#endif
mystreambuf.cpp
// Based on class by perfectly.insane from http://www.dreamincode.net/code/snippet2499.htm
#include <fstream>
#include <iostream>
#include <streambuf>
#include "mystreambuf.h"
// This function is called when the output buffer is filled.
// In this function, the buffer should be written to wherever it should
// be written to (in this case, the streambuf object that this is controlling).
template <typename charT, typename traits>
typename mystreambuf<charT, traits>::int_type
mystreambuf<charT, traits>::overflow(typename mystreambuf<charT, traits>::int_type c)
{
charT* ibegin = this->out_buf_;
charT* iend = this->pptr();
// Reset the put pointers to indicate that the buffer is free
// (at least it will be at the end of this function).
setp(out_buf_, out_buf_ + BUFF_SIZE + 1);
// If this is the end, add an eof character to the buffer.
// This is why the pointers passed to setp are off by 1
// (to reserve room for this).
if(!traits_type::eq_int_type(c, traits_type::eof())) {
*iend++ = traits_type::to_char_type(c);
}
// Compute the write length.
int_type ilen = iend - ibegin;
// ADDED: restore cout to its original stream, output to it, output to the file, then set cout's stream back to this, our streambuf)
std::cout.rdbuf(original_cout);
out_buf_[ilen] = '\0';
std::cout << out_buf_;
outfile << out_buf_;
std::cout.rdbuf(this);
return traits_type::not_eof(c);
}
// This is called to flush the buffer.
// This is called when we're done with the file stream (or when .flush() is called).
template <typename charT, typename traits>
typename mystreambuf<charT, traits>::int_type
mystreambuf<charT, traits>::sync()
{
return traits_type::eq_int_type(this->overflow(traits_type::eof()),
traits_type::eof()) ? -1 : 0;
}
int main(int argc, char* argv[]) {
mystreambuf<char> filter(std::cout.rdbuf());
std::cout.rdbuf(&filter);
std::cout << "Hello World" << std::endl;
return 0;
}
희망이 도움이
mystreambuf.h 파일에 기록 할 것이다 환호
내가 가장 가까이에 올 수있는 것은 영리하게 작성된'#define' 또는 두 가지라고 생각합니다. – suszterpatt