]> git.scottworley.com Git - overonion/blobdiff - reverse_lib.c
Switch to stdio for output. It's simpler
[overonion] / reverse_lib.c
index dad7e0d733304ad1d7587dbc9dd006934c58bc27..46563562f3b3833d44a67b0809e5887c2abb949e 100644 (file)
@@ -1,26 +1,15 @@
 #define _FILE_OFFSET_BITS 64
 
-#define BUFFER_SIZE 4096
-
 #include <err.h>
 #include <fcntl.h>
+#include <stdio.h>
 #include <sys/mman.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <sysexits.h>
 #include <unistd.h>
 
-static void write_all(int fd, const void *buf, size_t count) {
-  const char* cbuf = buf;
-  size_t written = 0;
-  while (written < count) {
-    int ret = write(fd, &cbuf[written], count - written);
-    if (ret == -1) err(EX_IOERR, "Could not write");
-    written += ret;
-  }
-}
-
-void reverse_file(const char* input_filename, int output_fd) {
+void reverse_file(const char* input_filename, FILE* output_stream) {
   int fd = open(input_filename, O_RDONLY);
   if (fd == -1) err(EX_NOINPUT, "Could not open specified file");
 
@@ -33,17 +22,8 @@ void reverse_file(const char* input_filename, int output_fd) {
   char *m = mmap(NULL, map_size, PROT_READ, MAP_SHARED, fd, 0);
   if (m == MAP_FAILED) err(EX_NOINPUT, "Could not mmap input");
 
-  char buf[BUFFER_SIZE];
-  off_t buf_offset = 0;
   for (off_t p = stats.st_size - 1; p >= 0; p--) {
-    buf[buf_offset++] = m[p];
-    if (buf_offset >= BUFFER_SIZE) {
-      write_all(output_fd, buf, buf_offset);
-      buf_offset = 0;
-    }
-  }
-  if (buf_offset) {
-    write_all(output_fd, buf, buf_offset);
+    if (fputc(m[p], output_stream) == EOF) errx(EX_IOERR, "Could not write");
   }
 
   if (munmap(m, map_size) == -1) err(EX_IOERR, "Could not unmap input");