1 // (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com) 2 // (C) Copyright 2005-2007 Jonathan Turkanis 3 // Distributed under the Boost Software License, Version 1.0. (See accompanying 4 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.) 5 6 // See http://www.boost.org/libs/iostreams for documentation. 7 8 #ifndef BOOST_IOSTREAMS_UNIX2DOS_FILTER_FILTER_HPP_INCLUDED 9 #define BOOST_IOSTREAMS_UNIX2DOS_FILTER_FILTER_HPP_INCLUDED 10 11 #include <cassert> 12 #include <cstdio> // EOF. 13 #include <iostream> // cin, cout. 14 #include <boost/iostreams/concepts.hpp> 15 #include <boost/iostreams/filter/stdio.hpp> 16 #include <boost/iostreams/operations.hpp> 17 18 namespace boost { namespace iostreams { namespace example { 19 20 class unix2dos_stdio_filter : public stdio_filter { 21 private: do_filter()22 void do_filter() 23 { 24 int c; 25 while ((c = std::cin.get()) != EOF) { 26 if (c == '\n') 27 std::cout.put('\r'); 28 std::cout.put(c); 29 } 30 } 31 }; 32 33 class unix2dos_input_filter : public input_filter { 34 public: unix2dos_input_filter()35 unix2dos_input_filter() : has_linefeed_(false) { } 36 37 template<typename Source> get(Source & src)38 int get(Source& src) 39 { 40 if (has_linefeed_) { 41 has_linefeed_ = false; 42 return '\n'; 43 } 44 45 int c; 46 if ((c = iostreams::get(src)) == '\n') { 47 has_linefeed_ = true; 48 return '\r'; 49 } 50 51 return c; 52 } 53 54 template<typename Source> close(Source &)55 void close(Source&) { has_linefeed_ = false; } 56 private: 57 bool has_linefeed_; 58 }; 59 60 class unix2dos_output_filter : public output_filter { 61 public: unix2dos_output_filter()62 unix2dos_output_filter() : has_linefeed_(false) { } 63 64 template<typename Sink> put(Sink & dest,int c)65 bool put(Sink& dest, int c) 66 { 67 if (c == '\n') 68 return has_linefeed_ ? 69 put_char(dest, '\n') : 70 put_char(dest, '\r') ? 71 this->put(dest, '\n') : 72 false; 73 return iostreams::put(dest, c); 74 } 75 76 template<typename Sink> close(Sink &)77 void close(Sink&) { has_linefeed_ = false; } 78 private: 79 template<typename Sink> put_char(Sink & dest,int c)80 bool put_char(Sink& dest, int c) 81 { 82 bool result; 83 if ((result = iostreams::put(dest, c)) == true) { 84 has_linefeed_ = 85 c == '\r' ? 86 true : 87 c == '\n' ? 88 false : 89 has_linefeed_; 90 } 91 return result; 92 } 93 94 bool has_linefeed_; 95 }; 96 97 } } } // End namespaces example, iostreams, boost. 98 99 #endif // #ifndef BOOST_IOSTREAMS_UNIX2DOS_FILTER_FILTER_HPP_INCLUDED 100