1BSON_STREAMING_BSON(3) libbson BSON_STREAMING_BSON(3)
2
3
4
6filedescriptor or memory region. bson_writer_t provides a streaming writer
7which can be initialized with a memory region. (Streaming BSON to a file de‐
8scriptor is not yet supported.)
9
11 bson_reader_t provides a convenient API to read sequential BSON docu‐
12 ments from a file-descriptor or memory buffer. The bson_reader_read()
13 function will read forward in the underlying stream and return a bson_t
14 that can be inspected and iterated upon.
15
16 #include <stdio.h>
17 #include <bson/bson.h>
18
19 int
20 main (int argc, char *argv[])
21 {
22 bson_reader_t *reader;
23 const bson_t *doc;
24 bson_error_t error;
25 bool eof;
26
27 reader = bson_reader_new_from_file ("mycollection.bson", &error);
28
29 if (!reader) {
30 fprintf (stderr, "Failed to open file.\n");
31 return 1;
32 }
33
34 while ((doc = bson_reader_read (reader, &eof))) {
35 char *str = bson_as_canonical_extended_json (doc, NULL);
36 printf ("%s\n", str);
37 bson_free (str);
38 }
39
40 if (!eof) {
41 fprintf (stderr,
42 "corrupted bson document found at %u\n",
43 (unsigned) bson_reader_tell (reader));
44 }
45
46 bson_reader_destroy (reader);
47
48 return 0;
49 }
50
51 See bson_reader_new_from_fd(), bson_reader_new_from_file(), and
52 bson_reader_new_from_data() for more information.
53
55 bson_writer_t provides a convenient API to write a sequence of BSON
56 documents to a memory buffer that can grow with realloc(). The
57 bson_writer_begin() and bson_writer_end() functions will manage the un‐
58 derlying buffer while building the sequence of documents.
59
60 This could also be useful if you want to write to a network packet
61 while serializing the documents from a higher level language, (but do
62 so just after the packets header).
63
64 #include <stdio.h>
65 #include <bson/bson.h>
66 #include <assert.h>
67
68 int
69 main (int argc, char *argv[])
70 {
71 bson_writer_t *writer;
72 bson_t *doc;
73 uint8_t *buf = NULL;
74 size_t buflen = 0;
75 bool r;
76 int i;
77
78 writer = bson_writer_new (&buf, &buflen, 0, bson_realloc_ctx, NULL);
79
80 for (i = 0; i < 10000; i++) {
81 r = bson_writer_begin (writer, &doc);
82 assert (r);
83
84 r = BSON_APPEND_INT32 (doc, "i", i);
85 assert (r);
86
87 bson_writer_end (writer);
88 }
89
90 bson_free (buf);
91
92 return 0;
93 }
94
95 See bson_writer_new() for more information.
96
98 MongoDB, Inc
99
101 2017-present, MongoDB, Inc
102
103
104
105
1061.25.1 Nov 08, 2023 BSON_STREAMING_BSON(3)