将cerr输出到文件中 的程序有问题,求教
一本书上的例子: code 如下:
#include <fstream>
#include <csddlib>
using namesapce std;
int main()
{
ofstream error_file("error.dat");
if (!error_file) {
cerr << "Failed to open error_file.\n";
exit(EXIT_FAILURE);
}
cerr = error_file; //这句好像有问题
cerr << "This is an example error file.\n";
return(EXIT_SUCCESS);
}
程序不而能运行,什么原因?如何修改呢?
[解决办法]
IO标准库类型是不可以进行复制或是赋值的。
ofstream out1, out2;
out1 = out2这么做都是不可以。
你可以用引用或是指针
[解决办法]
#include <fstream>
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
ofstream error_file("error.dat");
if (!error_file) {
cerr << "Failed to open error_file.\n";
exit(EXIT_FAILURE);
}
error_file << "This is an example error file.\n";
return(EXIT_SUCCESS);
}
首先是你的cerr的用法不正确,必须加上头文件《iostream》,其次你的namespace拼写错误了,
最后文件操作不是这样子的。写文件的话使用与文件绑定的流对象,在你的程序中应该是error_file.
[解决办法]
#include <fstream>
#include <iostream> //cerr
#include <cstdlib>
using namespace std;
int main()
{
ofstream error_file("error.dat");
if (!error_file) {
cerr << "Failed to open error_file.\n";
exit(EXIT_FAILURE);
}
//cerr = error_file; //这句好像有问题
std::streambuf* pOldBuf = cerr.rdbuf(error_file.rdbuf());
cerr << "This is an example error file.\n"; //会被输出到文件中
return(EXIT_SUCCESS);
//restore buf
cerr.rdbuf(pOldBuf);
}