Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/freebsd-src
Path: blob/main/contrib/libcbor/examples/readfile.c
39586 views
1
/*
2
* Copyright (c) 2014-2020 Pavel Kalvoda <[email protected]>
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(void) {
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
free(buffer);
35
36
if (result.error.code != CBOR_ERR_NONE) {
37
printf(
38
"There was an error while reading the input near byte %zu (read %zu "
39
"bytes in total): ",
40
result.error.position, result.read);
41
switch (result.error.code) {
42
case CBOR_ERR_MALFORMATED: {
43
printf("Malformed data\n");
44
break;
45
}
46
case CBOR_ERR_MEMERROR: {
47
printf("Memory error -- perhaps the input is too large?\n");
48
break;
49
}
50
case CBOR_ERR_NODATA: {
51
printf("The input is empty\n");
52
break;
53
}
54
case CBOR_ERR_NOTENOUGHDATA: {
55
printf("Data seem to be missing -- is the input complete?\n");
56
break;
57
}
58
case CBOR_ERR_SYNTAXERROR: {
59
printf(
60
"Syntactically malformed data -- see "
61
"https://www.rfc-editor.org/info/std94\n");
62
break;
63
}
64
case CBOR_ERR_NONE: {
65
// GCC's cheap dataflow analysis gag
66
break;
67
}
68
}
69
exit(1);
70
}
71
72
/* Pretty-print the result */
73
cbor_describe(item, stdout);
74
fflush(stdout);
75
/* Deallocate the result */
76
cbor_decref(&item);
77
78
fclose(f);
79
}
80
81