c++ - 文件流和控制台流之间的区别

标签 c++ fstream ostream

如何判断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/

相关文章:

c++ - CMake add_executable 在另一个目录

c++ - 如何使用gnu autotool构建qt项目

c++ - 向后读取文件,c++ ifstream

c++ - 从无组织的文本文件中读取整数

c++ - "Where"这个重载运算符是否接受 "out"?

c++ - 如何跟踪写入 std::ostream 对象的字节数?

c++ - 关于C++boost图库的一些问题

c++ - VS 2012 更改默认调试 'Working Directory'

c++ - getline 返回空字符串

c++ - 为什么 std::setbase(2) 不切换到二进制输出?