unix2dos_filter.hpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. // See http://www.boost.org/libs/iostreams for documentation.
  6. #ifndef BOOST_IOSTREAMS_UNIX2DOS_FILTER_FILTER_HPP_INCLUDED
  7. #define BOOST_IOSTREAMS_UNIX2DOS_FILTER_FILTER_HPP_INCLUDED
  8. #include <cassert>
  9. #include <cstdio> // EOF.
  10. #include <iostream> // cin, cout.
  11. #include <boost/iostreams/concepts.hpp>
  12. #include <boost/iostreams/filter/stdio.hpp>
  13. #include <boost/iostreams/operations.hpp>
  14. namespace boost { namespace iostreams { namespace example {
  15. class unix2dos_stdio_filter : public stdio_filter {
  16. private:
  17. void do_filter()
  18. {
  19. int c;
  20. while ((c = std::cin.get()) != EOF) {
  21. if (c == '\n')
  22. std::cout.put('\r');
  23. std::cout.put(c);
  24. }
  25. }
  26. };
  27. class unix2dos_input_filter : public input_filter {
  28. public:
  29. unix2dos_input_filter() : has_linefeed_(false) { }
  30. template<typename Source>
  31. int get(Source& src)
  32. {
  33. if (has_linefeed_) {
  34. has_linefeed_ = false;
  35. return '\n';
  36. }
  37. int c;
  38. if ((c = iostreams::get(src)) == '\n') {
  39. has_linefeed_ = true;
  40. return '\r';
  41. }
  42. return c;
  43. }
  44. template<typename Source>
  45. void close(Source&) { has_linefeed_ = false; }
  46. private:
  47. bool has_linefeed_;
  48. };
  49. class unix2dos_output_filter : public output_filter {
  50. public:
  51. unix2dos_output_filter() : has_linefeed_(false) { }
  52. template<typename Sink>
  53. bool put(Sink& dest, int c)
  54. {
  55. if (c == '\n')
  56. return has_linefeed_ ?
  57. put_char(dest, '\n') :
  58. put_char(dest, '\r') ?
  59. this->put(dest, '\n') :
  60. false;
  61. return iostreams::put(dest, c);
  62. }
  63. template<typename Sink>
  64. void close(Sink&) { has_linefeed_ = false; }
  65. private:
  66. template<typename Sink>
  67. bool put_char(Sink& dest, int c)
  68. {
  69. bool result;
  70. if ((result = iostreams::put(dest, c)) == true) {
  71. has_linefeed_ =
  72. c == '\r' ?
  73. true :
  74. c == '\n' ?
  75. false :
  76. has_linefeed_;
  77. }
  78. return result;
  79. }
  80. bool has_linefeed_;
  81. };
  82. } } } // End namespaces example, iostreams, boost.
  83. #endif // #ifndef BOOST_IOSTREAMS_UNIX2DOS_FILTER_FILTER_HPP_INCLUDED