Path: blob/main/contrib/libcbor/examples/streaming_array.c
39586 views
/*1* Copyright (c) 2014-2020 Pavel Kalvoda <[email protected]>2*3* libcbor is free software; you can redistribute it and/or modify4* it under the terms of the MIT license. See LICENSE for details.5*/67#include <stdlib.h>8#include "cbor.h"910void usage(void) {11printf("Usage: streaming_array <N>\n");12printf("Prints out serialized array [0, ..., N-1]\n");13exit(1);14}1516#define BUFFER_SIZE 817unsigned char buffer[BUFFER_SIZE];18FILE* out;1920void flush(size_t bytes) {21if (bytes == 0) exit(1); // All items should be successfully encoded22if (fwrite(buffer, sizeof(unsigned char), bytes, out) != bytes) exit(1);23if (fflush(out)) exit(1);24}2526/*27* Example of using the streaming encoding API to create an array of integers28* on the fly. Notice that a partial output is produced with every element.29*/30int main(int argc, char* argv[]) {31if (argc != 2) usage();32long n = strtol(argv[1], NULL, 10);33out = freopen(NULL, "wb", stdout);34if (!out) exit(1);3536// Start an indefinite-length array37flush(cbor_encode_indef_array_start(buffer, BUFFER_SIZE));38// Write the array items one by one39for (size_t i = 0; i < n; i++) {40flush(cbor_encode_uint32(i, buffer, BUFFER_SIZE));41}42// Close the array43flush(cbor_encode_break(buffer, BUFFER_SIZE));4445if (fclose(out)) exit(1);46}474849