在 C++ 中重定向
#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
?
更新:
我无法使用使用类或使用全局的解决方案,所以请一些 给我使用新的解决方案。另外,将 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;
}
#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;
}
Does cout write to the given file?
If not, is there a way to do it without sending the variables to foo, like new
?
update :
I can't use a solution that uses class or uses global so plz can some
give me solution that use new. Also passing the from main to foo
streambuf *psbuf;
ofstream filestr;
should work right?
I am trying to do this but its not working?
I pass the stream to foo so it exist in the main so it wont end when foo finish.
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我怀疑现在编译并运行你的代码并发现你遇到了分段错误。
您之所以得到这个,是因为您在
foo()
中创建并打开了一个ofstream
对象,然后该对象在foo
末尾被销毁(并关闭) >。当您尝试在main()
中写入流时,您尝试访问不再存在的缓冲区。一个解决方法是使您的
filestr
对象成为全局的。还有很多更好的!编辑:这是@MSalters建议的更好的解决方案:
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 withinfoo()
, which is then destroyed (and closed) at the end offoo
. When you attempt to write to the stream inmain()
, 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:
在我看来,你的代码应该可以工作,但是......你为什么不自己尝试一下呢?您将看到所有内容是否都写在 test.txt 中。
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.