bson_reader_t provides a streaming reader which can be initialized with a filedescriptor or memory region. bson_writer_t provides a streaming writer which can be initialized with a memory region. (Streaming BSON to a file descriptor is not yet supported.)

bson_reader_t provides a convenient API to read sequential BSON documents from a file-descriptor or memory buffer. The bson_reader_read() function will read forward in the underlying stream and return a bson_t that can be inspected and iterated upon.

#include<stdio.h>#include<bson.h>intmain(intargc,char*argv[]){bson_reader_t*reader;constbson_t*doc;bson_error_terror;booleof;reader=bson_reader_new_from_file("mycollection.bson",&error);if(!reader){fprintf(stderr,"Failed to open file.\n");return1;}while((doc=bson_reader_read(reader,&eof))){char*str=bson_as_canonical_extended_json(doc,NULL);printf("%s\n",str);bson_free(str);}if(!eof){fprintf(stderr,"corrupted bson document found at %u\n",(unsigned)bson_reader_tell(reader));}bson_reader_destroy(reader);return0;}

bson_writer_t provides a convenient API to write a sequence of BSON documents to a memory buffer that can grow with realloc(). The bson_writer_begin() and bson_writer_end() functions will manage the underlying buffer while building the sequence of documents.

This could also be useful if you want to write to a network packet while serializing the documents from a higher level language, (but do so just after the packets header).