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