]>
Commit | Line | Data |
---|---|---|
b398ee5a SW |
1 | #define _FILE_OFFSET_BITS 64 |
2 | ||
3 | #define BUFFER_SIZE 4096 | |
4 | ||
b398ee5a | 5 | #include <err.h> |
3adfbe9d SW |
6 | #include <fcntl.h> |
7 | #include <sys/mman.h> | |
8 | #include <sys/stat.h> | |
9 | #include <sys/types.h> | |
b398ee5a | 10 | #include <sysexits.h> |
3adfbe9d | 11 | #include <unistd.h> |
b398ee5a SW |
12 | |
13 | static 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); | |
3a85da3a | 18 | if (ret == -1) err(EX_IOERR, "Could not write"); |
b398ee5a SW |
19 | written += ret; |
20 | } | |
21 | } | |
22 | ||
20615086 | 23 | void reverse_file(const char* input_filename, int output_fd) { |
b398ee5a | 24 | int fd = open(input_filename, O_RDONLY); |
3a85da3a | 25 | if (fd == -1) err(EX_NOINPUT, "Could not open specified file"); |
b398ee5a SW |
26 | |
27 | struct stat stats; | |
3a85da3a | 28 | if (fstat(fd, &stats) == -1) err(EX_NOINPUT, "Could not stat input"); |
b398ee5a SW |
29 | |
30 | long page_size = sysconf(_SC_PAGE_SIZE); | |
31 | off_t pages = (stats.st_size - 1) / page_size + 1; | |
32 | long map_size = pages * page_size; | |
33 | char *m = mmap(NULL, map_size, PROT_READ, MAP_SHARED, fd, 0); | |
3a85da3a | 34 | if (m == MAP_FAILED) err(EX_NOINPUT, "Could not mmap input"); |
b398ee5a SW |
35 | |
36 | char buf[BUFFER_SIZE]; | |
37 | off_t buf_offset = 0; | |
38 | for (off_t p = stats.st_size - 1; p >= 0; p--) { | |
39 | buf[buf_offset++] = m[p]; | |
40 | if (buf_offset >= BUFFER_SIZE) { | |
20615086 | 41 | write_all(output_fd, buf, buf_offset); |
b398ee5a SW |
42 | buf_offset = 0; |
43 | } | |
44 | } | |
45 | if (buf_offset) { | |
20615086 | 46 | write_all(output_fd, buf, buf_offset); |
b398ee5a SW |
47 | } |
48 | ||
3a85da3a SW |
49 | if (munmap(m, map_size) == -1) err(EX_IOERR, "Could not unmap input"); |
50 | if (close(fd) == -1) err(EX_IOERR, "Could not close input"); | |
b398ee5a | 51 | } |