#include "reverse_lib.h"
#include <err.h>
+#include <stdio.h>
#include <sysexits.h>
int main(int argc, char** argv) {
errx(EX_USAGE, "Usage: reverse filename");
}
- reverse_file(argv[1], 1);
+ reverse_file(argv[1], stdout);
return 0;
}
#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");
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");
#ifndef _OVERONION_REVERSE_LIB_H
#define _OVERONION_REVERSE_LIB_H
-/* Copy the contents of input_filename to output_fd backwards.
+#include <stdio.h>
+
+/* Copy the contents of input_filename to output_stream backwards.
* input_filename must be a real file, not a pipe. */
-void reverse_file(const char* input_filename, int output_fd);
+void reverse_file(const char* input_filename, FILE* output_stream);
#endif /* _OVERONION_REVERSE_LIB_H */
char* temp_filename = strdup("/tmp/reverse_test.XXXXXX");
int fd = mkstemp(temp_filename);
if (fd == -1) err(EX_IOERR, "Couldn't make a temporary file");
- reverse_file(input_file, fd);
- if (close(fd) == -1) err(EX_IOERR, "Couldn't close temporary file");
+ FILE* f = fdopen(fd, "w");
+ if (f == NULL) err(EX_IOERR, "Couldn't open temporary file");
+ reverse_file(input_file, f);
+ if (fclose(f) == EOF) err(EX_IOERR, "Couldn't close temporary file");
return temp_filename;
}