xref: /freebsd/contrib/libcbor/examples/readfile.c (revision 10ff414c14eef433d8157f0c17904d740693933b)
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 <stdio.h>
9 #include "cbor.h"
10 
11 void usage() {
12   printf("Usage: readfile [input file]\n");
13   exit(1);
14 }
15 
16 /*
17  * Reads data from a file. Example usage:
18  * $ ./examples/readfile examples/data/nested_array.cbor
19  */
20 
21 int main(int argc, char* argv[]) {
22   if (argc != 2) usage();
23   FILE* f = fopen(argv[1], "rb");
24   if (f == NULL) usage();
25   fseek(f, 0, SEEK_END);
26   size_t length = (size_t)ftell(f);
27   fseek(f, 0, SEEK_SET);
28   unsigned char* buffer = malloc(length);
29   fread(buffer, length, 1, f);
30 
31   /* Assuming `buffer` contains `length` bytes of input data */
32   struct cbor_load_result result;
33   cbor_item_t* item = cbor_load(buffer, length, &result);
34 
35   if (result.error.code != CBOR_ERR_NONE) {
36     printf(
37         "There was an error while reading the input near byte %zu (read %zu "
38         "bytes in total): ",
39         result.error.position, result.read);
40     switch (result.error.code) {
41       case CBOR_ERR_MALFORMATED: {
42         printf("Malformed data\n");
43         break;
44       }
45       case CBOR_ERR_MEMERROR: {
46         printf("Memory error -- perhaps the input is too large?\n");
47         break;
48       }
49       case CBOR_ERR_NODATA: {
50         printf("The input is empty\n");
51         break;
52       }
53       case CBOR_ERR_NOTENOUGHDATA: {
54         printf("Data seem to be missing -- is the input complete?\n");
55         break;
56       }
57       case CBOR_ERR_SYNTAXERROR: {
58         printf(
59             "Syntactically malformed data -- see "
60             "http://tools.ietf.org/html/rfc7049\n");
61         break;
62       }
63       case CBOR_ERR_NONE: {
64         // GCC's cheap dataflow analysis gag
65         break;
66       }
67     }
68     exit(1);
69   }
70 
71   /* Pretty-print the result */
72   cbor_describe(item, stdout);
73   fflush(stdout);
74   /* Deallocate the result */
75   cbor_decref(&item);
76 
77   fclose(f);
78 }
79