Add helper functions for reading/writing binary files.
This commit is contained in:
parent
5188f5c25f
commit
8f61648a39
@ -20,6 +20,12 @@
|
||||
*/
|
||||
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <io.h>
|
||||
#include <fcntl.h>
|
||||
#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;
|
||||
}
|
||||
|
||||
@ -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 */
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user