Redirecting in C++

后端 未结 2 693
闹比i
闹比i 2021-01-24 06:29
#include 
#include 
using namespace std;

void foo(){
  streambuf *psbuf;
  ofstream filestr;
  filestr.open (\"test.txt\");
  psbuf = fil         


        
相关标签:
2条回答
  • 2021-01-24 06:59

    I suspect that by now compiled and run your code and found that you get a segmentation fault.

    You are getting this because you create and open an ofstream object within foo(), which is then destroyed (and closed) at the end of foo. When you attempt to write to the stream in main(), you attempt to access a buffer which no longer exists.

    One workaround to this is to make your filestr object global. There are plenty of better ones!

    Edit: Here is a better solution as suggested by @MSalters:

    #include <iostream>
    #include <fstream>
    
    class scoped_cout_redirector
    {
    public:
        scoped_cout_redirector(const std::string& filename)
            :backup_(std::cout.rdbuf())
            ,filestr_(filename.c_str())
            ,sbuf_(filestr_.rdbuf())
        {
            std::cout.rdbuf(sbuf_);
        }
    
        ~scoped_cout_redirector()
        {
            std::cout.rdbuf(backup_);
        }
    
    private:
        scoped_cout_redirector();
        scoped_cout_redirector(const scoped_cout_redirector& copy);
        scoped_cout_redirector& operator =(const scoped_cout_redirector& assign);
    
        std::streambuf* backup_;
        std::ofstream filestr_;
        std::streambuf* sbuf_;
    };
    
    
    int main()
    {
        {
            scoped_cout_redirector file1("file1.txt");
            std::cout << "This is written to the first file." << std::endl;
        }
    
    
        std::cout << "This is written to stdout." << std::endl;
    
        {
            scoped_cout_redirector file2("file2.txt");
            std::cout << "This is written to the second file." << std::endl;
        }
    
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-24 07:18

    It seems to me that your code should work but ... Why don't you try yourself ? You will see if everything is written in test.txt or not.

    0 讨论(0)
提交回复
热议问题