1 /*
2 * Copyright (c) 2014-2019 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 <stdio.h>
9 #include <string.h>
10 #include "cbor.h"
11
usage()12 void usage() {
13 printf("Usage: streaming_parser [input file]\n");
14 exit(1);
15 }
16
17 /*
18 * Illustrates how one might skim through a map (which is assumed to have
19 * string keys and values only), looking for the value of a specific key
20 *
21 * Use the examples/data/map.cbor input to test this.
22 */
23
24 const char* key = "a secret key";
25 bool key_found = false;
26
find_string(void * _ctx,cbor_data buffer,size_t len)27 void find_string(void* _ctx, cbor_data buffer, size_t len) {
28 if (key_found) {
29 printf("Found the value: %.*s\n", (int)len, buffer);
30 key_found = false;
31 } else if (len == strlen(key)) {
32 key_found = (memcmp(key, buffer, len) == 0);
33 }
34 }
35
main(int argc,char * argv[])36 int main(int argc, char* argv[]) {
37 if (argc != 2) usage();
38 FILE* f = fopen(argv[1], "rb");
39 if (f == NULL) usage();
40 fseek(f, 0, SEEK_END);
41 size_t length = (size_t)ftell(f);
42 fseek(f, 0, SEEK_SET);
43 unsigned char* buffer = malloc(length);
44 fread(buffer, length, 1, f);
45
46 struct cbor_callbacks callbacks = cbor_empty_callbacks;
47 struct cbor_decoder_result decode_result;
48 size_t bytes_read = 0;
49 callbacks.string = find_string;
50 while (bytes_read < length) {
51 decode_result = cbor_stream_decode(buffer + bytes_read, length - bytes_read,
52 &callbacks, NULL);
53 bytes_read += decode_result.read;
54 }
55
56 free(buffer);
57 fclose(f);
58 }
59