Introduce function write_buffer_to_file
authorSimon Guinot <simon.guinot@seagate.com>
Tue, 27 Jan 2015 13:26:12 +0000 (14:26 +0100)
committerSimon Guinot <simon.guinot@seagate.com>
Wed, 28 Jan 2015 15:32:31 +0000 (16:32 +0100)
The function write_buffer_to_file allows to write a buffer content
into a file.

buffer.c
buffer.h

index 3274877..0ae72de 100644 (file)
--- a/buffer.c
+++ b/buffer.c
  * along with netsum.  If not, see <http://www.gnu.org/licenses/>.
  */
 
+#define _GNU_SOURCE
 #include <stdlib.h>
 #include <stdio.h>
 #include <stdint.h>
 #include <errno.h>
 #include <string.h>
 #include <stdbool.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <linux/limits.h>
 
 #include "netsum.h"
 #include "crc32/crc32.h"
 #include "buffer.h"
 
+int write_buffer_to_file(const char *fname, unsigned char *buff, size_t size)
+{
+       int fd;
+       int retry;
+       int ret;
+       char fpath[PATH_MAX];
+       char *curr_dir;
+
+       curr_dir = get_current_dir_name();
+       if (curr_dir == NULL) {
+               fprintf(stderr, "get_current_dir_name() %s failed\n",
+               strerror(errno));
+               return -1;
+       }
+       snprintf(fpath, sizeof(fpath), "%s/%s", curr_dir, fname);
+       free(curr_dir);
+
+       fd = open(fpath, O_CREAT|O_TRUNC|O_WRONLY, 0644);
+       if (fd == -1) {
+               fprintf(stderr, "open() %s failed: %s\n", fpath,
+                       strerror(errno));
+               return -1;
+       }
+
+       retry = 0;
+       while (size && (retry < 3)) {
+               ret = write(fd, buff, size);
+               if (ret == -1) {
+                       if (errno == EAGAIN || errno == EINTR) {
+                               retry++;
+                               continue;
+                       }
+                       fprintf(stderr, "write() %s failed: %s\n",
+                               fpath, strerror(errno));
+                       return -1;
+               }
+               buff += ret;
+               size -= ret;
+       }
+
+       ret = close(fd);
+       if (ret == -1) {
+               fprintf(stderr, "close() %s failed: %s\n", fpath,
+                       strerror(errno));
+               return -1;
+       }
+
+       return 0;
+}
+
 void dump_buffer(unsigned char *buff, int size)
 {
         int i;
index bebed4b..cb29bd8 100644 (file)
--- a/buffer.h
+++ b/buffer.h
@@ -1,5 +1,6 @@
 #define MAX_BUFFER_SIZE 262144 /* 256 KB */
 
+int write_buffer_to_file(const char *fname, unsigned char *buff, size_t size);
 void dump_buffer(unsigned char *buffer, int size);
 void fill_buffer(unsigned char *buffer, int size);
 bool buffer_is_valid(unsigned char *buff, int size, bool verbose);