]> git.scottworley.com Git - overonion/blob - reverse.c
ac55a102c1fc2f8fd4d6513a99f182aade5aa8a7
[overonion] / reverse.c
1 #define _FILE_OFFSET_BITS 64
2
3 #define BUFFER_SIZE 4096
4
5 #include <sys/types.h>
6 #include <sys/stat.h>
7 #include <sys/mman.h>
8 #include <fcntl.h>
9 #include <unistd.h>
10 #include <err.h>
11 #include <sysexits.h>
12
13 void write_all(int fd, const void *buf, size_t count) {
14 const char* cbuf = buf;
15 size_t written = 0;
16 while (written < count) {
17 int ret = write(fd, &cbuf[written], count - written);
18 if (ret == -1) {
19 err(EX_IOERR, "Could not write");
20 }
21 written += ret;
22 }
23 }
24
25
26 int main(int argc, char** argv) {
27 if (argc != 2) {
28 errx(EX_USAGE, "Usage: reverse filename");
29 }
30
31 int fd = open(argv[1], O_RDONLY);
32 if (fd == -1) {
33 err(EX_NOINPUT, "Could not open specified file");
34 }
35
36 struct stat stats;
37 if (fstat(fd, &stats) == -1) {
38 err(EX_NOINPUT, "Could not stat input");
39 }
40
41 long page_size = sysconf(_SC_PAGE_SIZE);
42 off_t pages = (stats.st_size - 1) / page_size + 1;
43 long map_size = pages * page_size;
44 char *m = mmap(NULL, map_size, PROT_READ, MAP_SHARED, fd, 0);
45 if (m == MAP_FAILED) {
46 err(EX_NOINPUT, "Could not mmap input");
47 }
48
49 char buf[BUFFER_SIZE];
50 off_t buf_offset = 0;
51 for (off_t p = stats.st_size - 1; p >= 0; p--) {
52 buf[buf_offset++] = m[p];
53 if (buf_offset >= BUFFER_SIZE) {
54 write_all(1, buf, buf_offset);
55 buf_offset = 0;
56 }
57 }
58 if (buf_offset) {
59 write_all(1, buf, buf_offset);
60 }
61
62 if (munmap(m, map_size) == -1) {
63 err(EX_IOERR, "Could not unmap input");
64 }
65 if (close(fd) == -1) {
66 err(EX_IOERR, "Could not close input");
67 }
68
69 return 0;
70 }