FileSink

From Crypto++ Wiki
Jump to navigation Jump to search
FileSink
Documentation
#include <cryptopp/files.h>

A FileSink allows you to write data to a file using a BufferedTransformation. You can pass an existing ostream and the library will write to it. Or you can have the library open an ostream for you (in which case the file is opened with ios::trunc).

The companion source object is a FileSource.

Sources, filters and sinks are discussed at Pipelining. The pipeline article explains the design and shows you how to use them.

Constructor

FileSink (std::ostream &out)
FileSink (const char *filename, bool binary=true)

out is an existing standard ostream.

filename is the name of a file. The FileSink will open the file as an ostream and truncate it if it exists.

binary is passed to the underlying ostream.

When the library opens the stream, it is opened with the ios::trunc flag.

Examples

The following example demonstrates creation of a FileSink.

string filename;
FileSink f( filename, true /*binary*/ );

The following example demonstrates reading a file using a FileSource, and placing the contents of the file in a string. This is known as pipelining.

string s;
FileSource file( filename, true, new StringSink( s ) );

cout << s << endl;

true indicates the FileSource should propagate to all filters in the chain. A slightly more complicated example of pipelining is below. Before the FileSource is placed in the string, it is HexEncoded.

string s;
FileSource( filename, true, new HexEncoder( new StringSink( s ) ) );

cout << s << endl;

From above, note that the HexEncoder and StringSink created with new do not require explicit destruction - the FileSource will call delete on the HexEncoder, which in turns calls delete on the StringSink when it (the FileSource) is destroyed.

byte data[] = { 0x00, 0x01, 0x02, 0x03 };
string sink;

HexEncoder encoder;
encoder.Attach( new StringSink( sink ) );
    
encoder.Put( data, sizeof( data ) );
encoder.MessageEnd();

cout << sink << endl;

Downloads

No downloads.