The in-house utility library used in my workplace includes a elaborate and flexible set of classes for parsing CSV. But it came up short when I need to write to CSV: to do that, I have to use STL file output stream! In fact STL stream and .NET stream classes do not have read/write symmetry as well: They are easy to write formatted output to file but leave the file parsing up to the user. In retrospect, C printf and scanf does have read/write symmetry.

Sad to admit my Unicode file library article also does not have this symmetry. Let me first show you what I propose to do in greatly simplified pseudo-code. See the symmetry? Bulk of the verifying and parsing work are done in match function.

You can overload the << and >> for your defined types. First, I show you how to overload my library's << >> operators, then STL stream << >> ones. The both code are similar.

Overloaded Stream Operators

Say we have a Date structure, this is how to overload the operators. Yes, we make use of temporary local new_text::ofstream and new_text::ifstream to help us as they can be used like std::stringstream without opening a file!

Overloaded STL Stream Operators

Previously, we see overloaded operators for the library stream.. But we cannot use those for std::cout! We will see next how to overload STL stream operators. Note: we can do that because my library uses STL stream underneath to do the work.

Next, we see how to parse a date and RGB color from a INI file. The 2nd parameter of match should be set to false when we only wish to verify string conformed to the specified format and not waste computation to process it. The default value is true.

The source code is not shown to the reader in the article because it is merely the parsing code which is of no interest. Those who are keen to examine the source code, are free to download from the above link.

Reader may wonder my reason for writing these file stream articles because I did not hide my disdain for STL stream in my Unicode file library article. The reason for the change of mind is I have been pondering to submit my file library to Boost in the future. One of the Boost requirements is that the library has to support the last 3 version of every C++ compiler. The mere thought of having to back-port variadic templates to pre-C++11 compilers gives me shudders. Then the idea to write new file streams came to me as they are C++98/03, so as to make porting relatively easy. These stream class will be ported to my Unicode library.

To use the library, just include the header: NewTextStream.h. For those user who prefer to use Boost lexical_cast and trim, just define or uncomment the below macros in the header. The code is tested in VS2008 and GCC 4.4. Thank you for reading!