From 41df7e42b597161dc2f78c861b3b83a9d445428d Mon Sep 17 00:00:00 2001 From: Nathael Pajani Date: Sat, 19 May 2012 01:38:07 +0200 Subject: [PATCH] Adding utility function : write buffer to file --- isp_utils.c | 39 +++++++++++++++++++++++++++++++++++++++ isp_utils.h | 6 ++++-- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/isp_utils.c b/isp_utils.c index 950fd95..985abdf 100644 --- a/isp_utils.c +++ b/isp_utils.c @@ -27,6 +27,8 @@ #include +#define FILE_CREATE_MODE (S_IRUSR | S_IWUSR | S_IRGRP) + extern int trace_on; /* display data as in hexdump -C : @@ -291,3 +293,40 @@ int isp_uu_decode(char* dest, char* src, unsigned int orig_size) return new_size; } + + +/* ---- File utility functions ----------------------------------------------*/ + +int isp_buff_to_file(char* data, unsigned int len, char* filename) +{ + int ret = 0; + int out_fd = -1; + + /* Open file for writing if output is not stdout */ + if (strncmp(filename, "-", strlen(filename)) == 0) { + out_fd = STDOUT_FILENO; + } else { + out_fd = open(filename, (O_WRONLY | O_CREAT | O_TRUNC), FILE_CREATE_MODE); + if (out_fd <= 0) { + perror("Unable to open or create file for writing"); + printf("Tried to open \"%s\".\n", filename); + return -1; + } + } + + /* Write data to file */ + ret = write(out_fd, data, len); + if (ret != (int)len) { + perror("File write error"); + printf("Unable to write %u bytes of data to file \"%s\", returned %d !", + len, filename, ret); + ret = -2; + } + + /* Close file */ + if (out_fd != STDOUT_FILENO) { + close(out_fd); + } + + return ret; +} diff --git a/isp_utils.h b/isp_utils.h index 86c5a89..90e7926 100644 --- a/isp_utils.h +++ b/isp_utils.h @@ -37,10 +37,12 @@ int isp_serial_read(char* buf, unsigned int buf_size, unsigned int min_read); /* ---- UU_Encoding utility functions ----------------------------------------------*/ - -/* FIXME : This is a place-holder forr uuencode and uudecode functions !!! */ int isp_uu_encode(char* dest, char* src, unsigned int orig_size); int isp_uu_decode(char* dest, char* src, unsigned int orig_size); + +/* ---- File utility functions ----------------------------------------------*/ +int isp_buff_to_file(char* data, unsigned int len, char* filename); + #endif /* ISP_UTILS_H */ -- 2.43.0