1 /*
2 * Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
3 *
4 * libcbor is free software; you can redistribute it and/or modify
5 * it under the terms of the MIT license. See LICENSE for details.
6 */
7
8 #include <stdlib.h>
9 #include "cbor.h"
10
usage(void)11 void usage(void) {
12 printf("Usage: streaming_array <N>\n");
13 printf("Prints out serialized array [0, ..., N-1]\n");
14 exit(1);
15 }
16
17 #define BUFFER_SIZE 8
18 unsigned char buffer[BUFFER_SIZE];
19 FILE* out;
20
flush(size_t bytes)21 void flush(size_t bytes) {
22 if (bytes == 0) exit(1); // All items should be successfully encoded
23 if (fwrite(buffer, sizeof(unsigned char), bytes, out) != bytes) exit(1);
24 if (fflush(out)) exit(1);
25 }
26
27 /*
28 * Example of using the streaming encoding API to create an array of integers
29 * on the fly. Notice that a partial output is produced with every element.
30 */
main(int argc,char * argv[])31 int main(int argc, char* argv[]) {
32 if (argc != 2) usage();
33 size_t n;
34 scanf(argv[1], "%zu", &n);
35 out = freopen(NULL, "wb", stdout);
36 if (!out) exit(1);
37
38 // Start an indefinite-length array
39 flush(cbor_encode_indef_array_start(buffer, BUFFER_SIZE));
40 // Write the array items one by one
41 for (size_t i = 0; i < n; i++) {
42 flush(cbor_encode_uint32(i, buffer, BUFFER_SIZE));
43 }
44 // Close the array
45 flush(cbor_encode_break(buffer, BUFFER_SIZE));
46
47 if (fclose(out)) exit(1);
48 }
49