]>
Commit | Line | Data |
---|---|---|
1 | #define _FILE_OFFSET_BITS 64 | |
2 | ||
3 | #include <err.h> | |
4 | #include <fcntl.h> | |
5 | #include <stdio.h> | |
6 | #include <sys/mman.h> | |
7 | #include <sys/stat.h> | |
8 | #include <sys/types.h> | |
9 | #include <sysexits.h> | |
10 | #include <unistd.h> | |
11 | ||
12 | void reverse_file(const char* input_filename, FILE* output_stream) { | |
13 | int fd = open(input_filename, O_RDONLY); | |
14 | if (fd == -1) err(EX_NOINPUT, "Could not open specified file"); | |
15 | ||
16 | struct stat stats; | |
17 | if (fstat(fd, &stats) == -1) err(EX_NOINPUT, "Could not stat input"); | |
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); | |
23 | if (m == MAP_FAILED) err(EX_NOINPUT, "Could not mmap input"); | |
24 | ||
25 | for (off_t p = stats.st_size - 1; p >= 0; p--) { | |
26 | if (fputc(m[p], output_stream) == EOF) errx(EX_IOERR, "Could not write"); | |
27 | } | |
28 | ||
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"); | |
31 | } |