[C++-sig] V2: python file object as an ostream argument

Pearu Peterson pearu at cens.ioc.ee
Sun Jun 2 00:18:43 CEST 2002


On Sat, 1 Jun 2002, David Abrahams wrote:

> From: "Pearu Peterson" <pearu at cens.ioc.ee>
> 
> > I tried google but there I got very contradictionary results. E.g. in
> > gcc-2.95.3 there is ostdiostream to make this connection but in gcc-3.x
> > ostdiostream does not exist anymore.
> >
> > Any hints how to solve this issue are very much appeciated.
> 
> This question really has nothing to do with Python; you just want to know
> how to make an ostream given a FILE*. It's unfortunate that C++ doesn't
> have such a facility built-in. I think the right way to do this is to build
> a streambuf around the FILE*. I believe "The C++ Standard Library", by
> Nicolai Josuttis, contains the code for such a thing. You might also look
> at newsgroup postings by Dietmar Kuehl.

Thanks for the references.

Following (a rather buggy) example in

http://groups.google.com/groups?hl=en&lr=&safe=off&selm=86mtsc%248sh%241%40nnrp1.deja.com&rnum=4

I solved this issue as follows:
/////////////////////////////
#include <streambuf>

  class std_obuf: public std::streambuf {
  public:
    std_obuf(std::FILE* file): m_file(file) {}
  protected:
    std::streambuf::int_type overflow(std::streambuf::int_type c) {
      return std::fputc(c, m_file) ==EOF? std::streambuf::traits_type::eof(): c;
    }
    FILE* m_file;
  };

  void A_output(const A & a, PyObject* fp) {
    if (!PyFile_Check(fp)) {
      ...
      throw boost::python::error_already_set();
    }
    std::FILE* f = PyFile_AsFile(fp);
    std_obuf buf(f);
    std::ostream os(&buf);
    a.output(os);
  }
///////////////////////////////

And sorry being OT,
	Pearu






More information about the Cplusplus-sig mailing list