Overloading fstream's << and >> operators

This is a discussion on Overloading fstream's << and >> operators within the C++ Programming forums, part of the General Programming Boards category; The extraction and insertion operators for fstream only read/write from/to disk in human readable text form. I would like to ...

  1. #1
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,598

    Overloading fstream's << and >> operators

    The extraction and insertion operators for fstream only read/write from/to disk in human readable text form. I would like to override them so that when I set the flag to binary, the operators would work like a binary read or write would. I realize for structures I would use read and write, but to simply write single values read and write are a pain in the arse.

    How would I go about overloading << and >> relative to fstream binary mode? My guess is I probably need to derive from fstream and use basic_streambuf's protected buffer function members to extract/insert the data in binary mode?

    Any help would be appreciated.

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    No, it is much simpler. There are plenty of examples on the Web, if you google for operator overloading.

    Basically you need two non-member functions (declared friends, if the class data is otherwise inaccessible).

    The prototypes are
    Code:
    std::ostream& operator << (std::ostream& os, const MyClass&);
    std::istream& operator >> (std::istream& is, MyClass&);

  3. #3
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,598
    Yep. Just found the info on the web. Seems straightforward enough.

    Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Overloading << and >>
    By MMu in forum C++ Programming
    Replies: 1
    Last Post: 04-21-2008, 07:49 AM
  2. operators << and >>
    By crvenkapa in forum C++ Programming
    Replies: 1
    Last Post: 04-06-2007, 04:10 PM
  3. Compile errors with overloading >> operators
    By GMHummerH1 in forum C++ Programming
    Replies: 1
    Last Post: 12-19-2004, 07:13 PM
  4. << and >> overloading
    By Armatura in forum C++ Programming
    Replies: 2
    Last Post: 12-07-2003, 06:19 PM
  5. Overloading the << and >> operators
    By WebmasterMattD in forum C++ Programming
    Replies: 9
    Last Post: 10-15-2002, 06:22 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21