# Tutorial

## 2.2.2. Filter Usage Examples

Filters are generally used in conjunction with filtering streams and stream buffers. For example, suppose you have some text which you want to compress, then Base64 encode, then write to a file. If you have appropriate OutputFilters `compressor` and `base64_encoder`, you can do this as follows:[1]

    #include <boost/iostreams/device/file_descriptor.hpp>
    #include <boost/iostreams/filtering_stream.hpp>

    namespace io = boost::iostreams;

    int main()
    {
        io::filtering_ostream out;
        out.push(compressor());
        out.push(base64_encoder());
        out.push(file_sink("my_file.txt"));
        // write to out using std::ostream interface
    }

Like all filtering streams and stream buffers, `filtering_ostream` maintains an internal chain of Filters and Devices. (See also `chain`.) When data is written to this chain, it flows through the components in the order they were pushed. The last component pushed in the above example could be any model of Sink, including a `std::ostream` such as `std::cout`.

Now suppose you want to recoved the original data. If you have appropriate InputFilters `decompressor` and `base64_decoder`, you can accomplish this as follows as follows:[2]

    #include <boost/iostreams/device/file.hpp>
    #include <boost/iostreams/filtering_stream.hpp>

    namespace io = boost::iostreams;

    int main()
    {
        io::filtering_istream in;
        in.push(decompressor());
        in.push(base64_decoder());
        in.push(file_source("my_file.txt"));
        // read from in using std::istream interface
    }

Here you see another use of a filter chain. When data is read from the chain, it flows through the components in reverse order, beginning with the component pushed last. The last component pushed could be any model of Source, including a `std::istream` such as `std::cin`.

[1]Strictly speaking, it would be better to use a `file_descriptor_sink` instead of a `file_sink` here, because `file_descriptor_sink` never performs code conversion.

[2]Strictly speaking, it would be better to use a `file_descriptor_source` instead of a `file_source` here, because `file_descriptor_source` never performs code conversion.

Revised 20 May, 2004

© Copyright Jonathan Turkanis, 2004

Use, modification, and distribution are subject to the Boost Software License, Version 2.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)