如何判断ostream是文件还是控制台流。在下面的程序中,我想打印“Hello file!”在写入文件和“Hello console!”时在写入控制台时。我应该在第 17 行指定什么条件?
#include <fstream>
#include<iostream>
#include <string>
using namespace std;
class A{
public:
A(string msg):_str(msg){}
string str()const {return _str;};
private:
string _str;
};
ostream & operator << (ostream & os, const A & a)
{
if (os is ofstream) //this is line 17
os << "Hello file! " << a.str() << endl;
else
os << "Hello console! " << a.str() << endl;
return os;
}
int main()
{
A a("message");
ofstream ofile("test.txt");
if (!ofile)
cerr << "Unable to open file";
else
ofile << a; // "Hello file"
cout << a << endl; // "Hello console"
}
最佳答案
也许不漂亮,但是
std::streambuf const * coutbuf = std::cout.rdbuf();
std::streambuf const * cerrbuf = std::cerr.rdbuf();
ostream & operator << (ostream & os, const A & a)
{
std::streambuf const * osbuf = os.rdbuf();
if ( osbuf == coutbuf || osbuf == cerrbuf )
os << "Hello console! " << a.str() << endl;
else
os << "Hello file! " << a.str() << endl;
return os;
}
我们可以使用&os == &std::cout
,但标准输出可能会被重定向到文件,所以我认为最好改用streambuf 对象。 (请参阅 this answer 以更好地理解重定向的工作原理,以及比较 streambuf 可以安全解决问题的原因!)
关于c++ - 文件流和控制台流之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18081392/