From 6d0a0767ece8013d89d38431fd56c6a88072f00d Mon Sep 17 00:00:00 2001 From: Lukasz Pawelczyk Date: Mon, 9 May 2016 15:55:29 +0200 Subject: [PATCH] write_file()/read_file() functions added They are not used now, but they are very helpful for debugging and they will be used in future examples. Change-Id: Ia3cee5a67013543096cef45b04b649ce5faaf9e8 --- examples/misc.c | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ examples/misc.h | 4 +++ 2 files changed, 88 insertions(+) diff --git a/examples/misc.c b/examples/misc.c index bd951e9..b3a8fdc 100644 --- a/examples/misc.c +++ b/examples/misc.c @@ -1,5 +1,8 @@ #include #include +#include + +#include #include #include "misc.h" @@ -19,3 +22,84 @@ void debug_func(const char* buf) { puts(buf); } + +int write_file(const char *path, char *data, size_t data_len) +{ + size_t written = 0; + FILE *f; + + f = fopen(path, "w"); + if (f == NULL) + return -1; + + while (written != data_len) { + int ret = fwrite(data + written, 1, data_len - written, f); + + if (ferror(f) != 0) { + fclose(f); + return -1; + } + + written += ret; + } + + fclose(f); + return 0; +} + +#define BUF_SIZE 512 + +int read_file(const char *path, char **data, size_t *data_len) +{ + int ret; + char tmp[BUF_SIZE]; + char *buf = NULL; + size_t buf_len; + FILE *f; + + f = fopen(path, "r"); + if (f == NULL) + return -1; + + for(;;) { + size_t read = fread(tmp, 1, BUF_SIZE, f); + + if (read > 0) { + if (buf == NULL) { + buf = yaca_malloc(read); + if (buf == NULL) { + ret = -1; + break; + } + buf_len = 0; + } else { + char *new_buf = yaca_realloc(buf, buf_len + read); + if (new_buf == NULL) { + ret = -1; + break; + } + buf = new_buf; + } + + memcpy(buf + buf_len, tmp, read); + buf_len += read; + } + + if (ferror(f) != 0) { + ret = -1; + break; + } + + if (feof(f)) { + *data = buf; + *data_len = buf_len; + buf = NULL; + ret = 0; + break; + } + } + + fclose(f); + free(buf); + return ret; +} diff --git a/examples/misc.h b/examples/misc.h index a4436f5..7d89758 100644 --- a/examples/misc.h +++ b/examples/misc.h @@ -37,4 +37,8 @@ void dump_hex(const char *buf, void debug_func(const char* buf); +int write_file(const char *path, char *data, size_t data_len); + +int read_file(const char *path, char **data, size_t *data_len); + #endif /* MISC_H */ -- 2.7.4