Path: blob/main/contrib/libcbor/examples/cbor_sequence.c
178428 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 <string.h>910#include "cbor.h"1112void write_cbor_sequence(const char* filename) {13FILE* file = fopen(filename, "wb");14if (!file) {15fprintf(stderr, "Error: Could not open file %s for writing\n", filename);16return;17}1819// Create example CBOR items20cbor_item_t* int_item = cbor_build_uint32(42);21cbor_item_t* string_item = cbor_build_string("Hello, CBOR!");22cbor_item_t* array_item = cbor_new_definite_array(2);23assert(cbor_array_push(array_item, cbor_build_uint8(1)));24assert(cbor_array_push(array_item, cbor_build_uint8(2)));2526// Serialize and write items to the file27unsigned char* buffer;28size_t buffer_size;2930cbor_serialize_alloc(int_item, &buffer, &buffer_size);31fwrite(buffer, 1, buffer_size, file);32free(buffer);33cbor_decref(&int_item);3435cbor_serialize_alloc(string_item, &buffer, &buffer_size);36fwrite(buffer, 1, buffer_size, file);37free(buffer);38cbor_decref(&string_item);3940cbor_serialize_alloc(array_item, &buffer, &buffer_size);41fwrite(buffer, 1, buffer_size, file);42free(buffer);43cbor_decref(&array_item);4445fclose(file);46printf("CBOR sequence written to %s\n", filename);47}4849void read_cbor_sequence(const char* filename) {50FILE* file = fopen(filename, "rb");51if (!file) {52fprintf(stderr, "Error: Could not open file %s\n", filename);53return;54}5556fseek(file, 0, SEEK_END);57size_t file_size = ftell(file);58fseek(file, 0, SEEK_SET);5960unsigned char* buffer = malloc(file_size);61if (!buffer) {62fprintf(stderr, "Error: Could not allocate memory\n");63fclose(file);64return;65}6667fread(buffer, 1, file_size, file);68fclose(file);6970struct cbor_load_result result;71size_t offset = 0;7273while (offset < file_size) {74cbor_item_t* item = cbor_load(buffer + offset, file_size - offset, &result);75if (result.error.code != CBOR_ERR_NONE) {76fprintf(stderr, "Error: Failed to parse CBOR item at offset %zu\n",77offset);78break;79}8081cbor_describe(item, stdout);82printf("\n");8384offset += result.read;85cbor_decref(&item);86}8788free(buffer);89}9091int main(int argc, char* argv[]) {92if (argc != 3) {93fprintf(stderr, "Usage: %s <r|w> <file>\n", argv[0]);94return 1;95}9697if (strcmp(argv[1], "w") == 0) {98write_cbor_sequence(argv[2]);99} else if (strcmp(argv[1], "r") == 0) {100read_cbor_sequence(argv[2]);101} else {102fprintf(stderr,103"Error: First argument must be 'r' (read) or 'w' (write)\n");104return 1;105}106107return 0;108}109110111