#include <iostream>
#include <fstream>
using namespace std;
void foo(){
streambuf *psbuf;
ofstream filestr;
filestr.open ("test.txt");
psbuf = filestr.rdbuf();
cout.rdbuf(psbuf);
}
int main () {
foo();
cout << "This is written to the file";
return 0;
}
cout 是否写入给定文件?
如果没有,有没有办法在不将变量发送到 foo 的情况下做到这一点,例如new
?
update :
我无法使用使用类或使用全局的解决方案,所以请一些
给我使用新的解决方案。还将从 main 传递到 foo
streambuf *psbuf;
ofstream filestr;
应该工作正常吗?
我正在尝试这样做,但它不起作用?
我将流传递给 foo ,因此它存在于 main 中,因此当 foo 完成时它不会结束。
void foo(streambuf *psbuf){
ofstream filestr;
filestr.open ("test.txt");
psbuf = filestr.rdbuf();
cout.rdbuf(psbuf);
}
int main () {
streambuf *psbuf
foo(psbuf);
cout << "This is written to the file";
return 0;
}
我怀疑现在编译并运行你的代码并发现你遇到了分段错误。
您得到这个是因为您创建并打开了一个ofstream
对象内foo()
,然后在结束时被销毁(并关闭)foo
。当您尝试写入流时main()
,您尝试访问不再存在的缓冲区。
One解决这个问题的方法是让你的filestr
对象全局。还有很多更好的!
Edit:这是 @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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)