]>
git.scottworley.com Git - overonion/blob - reverse_lib.c
a800db84dce4cdf1e7a30e5ca909562c171a8042
1 #define _FILE_OFFSET_BITS 64
3 #define BUFFER_SIZE 4096
13 static void write_all(int fd
, const void *buf
, size_t count
) {
14 const char* cbuf
= buf
;
16 while (written
< count
) {
17 int ret
= write(fd
, &cbuf
[written
], count
- written
);
19 err(EX_IOERR
, "Could not write");
25 void reverse_file(const char* input_filename
) {
26 int fd
= open(input_filename
, O_RDONLY
);
28 err(EX_NOINPUT
, "Could not open specified file");
32 if (fstat(fd
, &stats
) == -1) {
33 err(EX_NOINPUT
, "Could not stat input");
36 long page_size
= sysconf(_SC_PAGE_SIZE
);
37 off_t pages
= (stats
.st_size
- 1) / page_size
+ 1;
38 long map_size
= pages
* page_size
;
39 char *m
= mmap(NULL
, map_size
, PROT_READ
, MAP_SHARED
, fd
, 0);
40 if (m
== MAP_FAILED
) {
41 err(EX_NOINPUT
, "Could not mmap input");
44 char buf
[BUFFER_SIZE
];
46 for (off_t p
= stats
.st_size
- 1; p
>= 0; p
--) {
47 buf
[buf_offset
++] = m
[p
];
48 if (buf_offset
>= BUFFER_SIZE
) {
49 write_all(1, buf
, buf_offset
);
54 write_all(1, buf
, buf_offset
);
57 if (munmap(m
, map_size
) == -1) {
58 err(EX_IOERR
, "Could not unmap input");
60 if (close(fd
) == -1) {
61 err(EX_IOERR
, "Could not close input");