• 16
• 15
• 11
• 9
• 10

c++ iostream

This topic is 3936 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

What I am looking for, is a way to read/write from/to a socket using C++'s iostreams. More generally a way of using iostream on any file descriptor, be it a fd coming from a network socket, pipe, file ... I am not sure how to acheive this using iostream.

Share on other sites
C++ iostreams sit a layer above file descriptors, there is no way of telling one to use a certain fd.

What you can do is replace the streambuf it uses, you could replace its streambuf with one that will write to an arbitrary file descriptor.

That may look hard (or at best confusing, lots of member functions with odd names), but in reality just implementing the rest of this class will get you started (for output anyway):
class MyStreamBuf : public std::basic_streambuf<char, std::char_traits<char> >{public:    typedef std::char_traits<char> Traits;    typedef std::basic_streambuf<char, Traits>::traits_type traits_type;    typedef std::basic_streambuf<char, Traits>::int_type    int_type;	protected:    // Function called by an ostream when it's time to send something out.    //    // @param c The value to be written out (generally a single character).    //    // @returns A value equal to traits_type::eof() on failure,    // traits_type::not_eof() on success.	int_type overflow(int_type c = traits_type::eof());};

Cheers to Bregma for the reference implementation provided here, which I've cut down.