C++ 阻塞流重定向的分段错误
这是我正在使用的代码的一个非常精简的版本。我已经将原始代码缩减到这几行,以便在程序运行结束时分离出一个分段错误C++ 阻塞流重定向的分段错误,c++,c,C++,C,这是我正在使用的代码的一个非常精简的版本。我已经将原始代码缩减到这几行,以便在程序运行结束时分离出一个分段错误 #include <iostream> #include <fstream> #include <string> int main(int argc, char *argv[]) { std::string cerr_file("cerr.out"); std::string clog_file("clog.out");
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char *argv[]) {
std::string cerr_file("cerr.out");
std::string clog_file("clog.out");
std::ofstream clogstream(clog_file, std::ofstream::out);
std::ofstream cerrstream(cerr_file, std::ofstream::out);
std::clog.rdbuf(clogstream.rdbuf());
std::cerr.rdbuf(cerrstream.rdbuf());
std::clog<<"Logging to clog"<<std::endl;
clogstream.close();
cerrstream.close();
}
#包括
#包括
#包括
int main(int argc,char*argv[]){
字符串cerr_文件(“cerr.out”);
std::字符串阻塞文件(“clog.out”);
std::ofstream clogstream(阻塞文件,std::ofstream::out);
std::of stream cerrstream(cerr_文件,std::of stream::out);
std::clog.rdbuf(clogstream.rdbuf());
std::cerr.rdbuf(cerstream.rdbuf());
std::clog您需要恢复以前的rdbuf,您可以这样做
std::string cerr_file("cerr.out");
std::string clog_file("clog.out");
std::ofstream clogstream(clog_file, std::ofstream::out);
std::ofstream cerrstream(cerr_file, std::ofstream::out);
std::streambuf* prevclogbuf = std::clog.rdbuf(clogstream.rdbuf());
std::streambuf* prevcerrbuf = std::cerr.rdbuf(cerrstream.rdbuf());
std::clog<<"Logging to clog"<<std::endl;
// Restore the previous streambuf
std::clog.rdbuf(prevclogbuf);
std::cerr.rdbuf(prevcerrbuf);
clogstream.close();
cerrstream.close();
std::string cerr_文件(“cerr.out”);
std::字符串阻塞文件(“clog.out”);
std::ofstream clogstream(阻塞文件,std::ofstream::out);
std::of stream cerrstream(cerr_文件,std::of stream::out);
std::streambuf*prevclogbuf=std::clog.rdbuf(clogstream.rdbuf());
std::streambuf*prevcerrbuf=std::cerr.rdbuf(cerrstream.rdbuf());
std::clog您需要恢复以前的rdbuf,您可以这样做
std::string cerr_file("cerr.out");
std::string clog_file("clog.out");
std::ofstream clogstream(clog_file, std::ofstream::out);
std::ofstream cerrstream(cerr_file, std::ofstream::out);
std::streambuf* prevclogbuf = std::clog.rdbuf(clogstream.rdbuf());
std::streambuf* prevcerrbuf = std::cerr.rdbuf(cerrstream.rdbuf());
std::clog<<"Logging to clog"<<std::endl;
// Restore the previous streambuf
std::clog.rdbuf(prevclogbuf);
std::cerr.rdbuf(prevcerrbuf);
clogstream.close();
cerrstream.close();
std::string cerr_文件(“cerr.out”);
std::字符串阻塞文件(“clog.out”);
std::ofstream clogstream(阻塞文件,std::ofstream::out);
std::of stream cerrstream(cerr_文件,std::of stream::out);
std::streambuf*prevclogbuf=std::clog.rdbuf(clogstream.rdbuf());
std::streambuf*prevcerrbuf=std::cerr.rdbuf(cerrstream.rdbuf());
clogJohn,谢谢,这解决了问题。我知道如何恢复缓冲区,但我决定不这样做,因为我认为这不可能,因为程序即将结束。你认为我的想法哪里错了?clog和cerr在其析构函数中删除缓冲区。因为clogstream/cerrstream有alr已经删除了他们的缓冲区,您正在双重删除。请特别参阅最后一个答案John,谢谢,这解决了问题。我知道如何恢复缓冲区,但我决定不这样做,因为程序即将结束。您认为我的想法哪里错了?clog和cerr delete它们的缓冲区在析构函数中。因为clogstream/cerrstream已经删除了它们的缓冲区,所以您正在双重删除。请特别参阅最后一个答案