From 8f61648a39f8341bbc9e4980d2ebd0c8349c770a Mon Sep 17 00:00:00 2001 From: Jef Driesen Date: Mon, 28 Dec 2015 09:00:06 +0100 Subject: [PATCH] Add helper functions for reading/writing binary files. --- examples/common.c | 65 +++++++++++++++++++++++++++++++++++++++++++++++ examples/common.h | 6 +++++ 2 files changed, 71 insertions(+) diff --git a/examples/common.c b/examples/common.c index d329635..ee552cd 100644 --- a/examples/common.c +++ b/examples/common.c @@ -20,6 +20,12 @@ */ #include +#include + +#ifdef _WIN32 +#include +#include +#endif #include "common.h" #include "utils.h" @@ -225,3 +231,62 @@ dctool_descriptor_search (dc_descriptor_t **out, const char *name, dc_family_t f return DC_STATUS_SUCCESS; } + +void +dctool_file_write (const char *filename, dc_buffer_t *buffer) +{ + FILE *fp = NULL; + + // Open the file. + if (filename) { + fp = fopen (filename, "wb"); + } else { + fp = stdout; +#ifdef _WIN32 + // Change from text mode to binary mode. + _setmode (_fileno (fp), _O_BINARY); +#endif + } + if (fp == NULL) + return; + + // Write the entire buffer to the file. + fwrite (dc_buffer_get_data (buffer), 1, dc_buffer_get_size (buffer), fp); + + // Close the file. + fclose (fp); +} + +dc_buffer_t * +dctool_file_read (const char *filename) +{ + FILE *fp = NULL; + + // Open the file. + if (filename) { + fp = fopen (filename, "rb"); + } else { + fp = stdin; +#ifdef _WIN32 + // Change from text mode to binary mode. + _setmode (_fileno (fp), _O_BINARY); +#endif + } + if (fp == NULL) + return NULL; + + // Allocate a memory buffer. + dc_buffer_t *buffer = dc_buffer_new (0); + + // Read the entire file into the buffer. + size_t n = 0; + unsigned char block[1024] = {0}; + while ((n = fread (block, 1, sizeof (block), fp)) > 0) { + dc_buffer_append (buffer, block, n); + } + + // Close the file. + fclose (fp); + + return buffer; +} diff --git a/examples/common.h b/examples/common.h index 09f5524..55dbb91 100644 --- a/examples/common.h +++ b/examples/common.h @@ -45,6 +45,12 @@ dctool_event_cb (dc_device_t *device, dc_event_type_t event, const void *data, v dc_status_t dctool_descriptor_search (dc_descriptor_t **out, const char *name, dc_family_t family, unsigned int model); +void +dctool_file_write (const char *filename, dc_buffer_t *buffer); + +dc_buffer_t * +dctool_file_read (const char *filename); + #ifdef __cplusplus } #endif /* __cplusplus */