将 std::ofstream 重定向到 std::cout 时失败

Fail while redirect a std::ofstream to std::cout

提问人:ivanovIAVD 提问时间:11/12/2020 最后编辑:YksisarvinenivanovIAVD 更新时间:11/12/2020 访问量:97

问:

我想将 std 重定向到一个文件。 为此,我编写了一个 ,其中我连接/断开 .class FoowriteToFilEnabled

但是,存在分段错误。这是怎么回事?

#include <iostream>
#include <fstream>

class Foo {
public:
    Foo() {
        out.open("out.txt");
        coutbuf = std::cout.rdbuf();
    }
    
    void writeToFileEnabled(bool enabled) {
        if (enabled)
            std::cout.rdbuf(out.rdbuf());
        else
            std::cout.rdbuf(coutbuf);
    }
    
    void test(int a) {
        std::cout << a << "\n";
    }
private:
    std::ofstream out;
    std::streambuf * coutbuf;
};

int main()
{
    Foo foo;
    
    foo.test(1);
    foo.test(2);
    foo.writeToFileEnabled(true);
    
    foo.test(3);
    foo.test(4);
}
C++ 重定向 cout ofstream streambuf

评论

1赞 Yksisarvinen 11/12/2020
你检查过是否退货吗?out.is_open()true
0赞 Anonymous1847 11/12/2020
您正在做的可能不是使用标准库,该库期望进入并可能基于此进行优化。试试吧?std::coutstdoutstd::cin.tie(nullptr)
0赞 Anonymous1847 11/12/2020
另请注意,在 POSIX 上,您可以使用 .stdoutfreopen
0赞 ivanovIAVD 11/12/2020
@Anonymous1847、不想打断POSIX和std
0赞 ivanovIAVD 11/12/2020
@Yksisarvinen,另外可以检查一下

答:

0赞 user11498001 11/12/2020 #1

你的 foo 对象是 main 函数中的局部变量,所以当 main 返回时,foo 被销毁,cout 持有指向你现在被销毁的 ofstream 的指针。当程序退出时,退出处理程序会尝试破坏 cout,这会导致它访问无效的 Foo::out 对象并使程序崩溃。您可以尝试将 foo 放在全局范围内,或者在 main 函数的末尾调用 foo.writeToFileEnabled(false)。

评论

1赞 ivanovIAVD 11/12/2020
好的,也许在析构函数调用中?std::cout.rdbuf(coutbuf)