]> git.scottworley.com Git - overonion/blame - reverse_lib.c
Switch to stdio for output. It's simpler
[overonion] / reverse_lib.c
CommitLineData
b398ee5a
SW
1#define _FILE_OFFSET_BITS 64
2
b398ee5a 3#include <err.h>
3adfbe9d 4#include <fcntl.h>
a99e77b4 5#include <stdio.h>
3adfbe9d
SW
6#include <sys/mman.h>
7#include <sys/stat.h>
8#include <sys/types.h>
b398ee5a 9#include <sysexits.h>
3adfbe9d 10#include <unistd.h>
b398ee5a 11
a99e77b4 12void reverse_file(const char* input_filename, FILE* output_stream) {
b398ee5a 13 int fd = open(input_filename, O_RDONLY);
3a85da3a 14 if (fd == -1) err(EX_NOINPUT, "Could not open specified file");
b398ee5a
SW
15
16 struct stat stats;
3a85da3a 17 if (fstat(fd, &stats) == -1) err(EX_NOINPUT, "Could not stat input");
b398ee5a
SW
18
19 long page_size = sysconf(_SC_PAGE_SIZE);
20 off_t pages = (stats.st_size - 1) / page_size + 1;
21 long map_size = pages * page_size;
22 char *m = mmap(NULL, map_size, PROT_READ, MAP_SHARED, fd, 0);
3a85da3a 23 if (m == MAP_FAILED) err(EX_NOINPUT, "Could not mmap input");
b398ee5a 24
b398ee5a 25 for (off_t p = stats.st_size - 1; p >= 0; p--) {
a99e77b4 26 if (fputc(m[p], output_stream) == EOF) errx(EX_IOERR, "Could not write");
b398ee5a
SW
27 }
28
3a85da3a
SW
29 if (munmap(m, map_size) == -1) err(EX_IOERR, "Could not unmap input");
30 if (close(fd) == -1) err(EX_IOERR, "Could not close input");
b398ee5a 31}