Last active
October 1, 2017 19:23
-
-
Save albinoloverats/562cf1f72262bc4ffe5f to your computer and use it in GitHub Desktop.
XOR two files together
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* gcc -std=gnu99 -O2 -s -o otp otp.c | |
*/ | |
#include <errno.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <fcntl.h> | |
#include <unistd.h> | |
#include <sys/stat.h> | |
#include <sys/mman.h> | |
#include <inttypes.h> | |
#include <string.h> | |
#define error_file(action, file) { fprintf(stderr, "Could not " #action " %s : %s\n", file, strerror(errno)); exit(errno); } | |
int main (int argc, char **argv) | |
{ | |
if (argc != 3 && argc != 4) | |
return fprintf(stderr, "Usage: %s <source> <source> [output]\n", argv[0]), EXIT_FAILURE; | |
int64_t in1 = open(argv[1], O_RDONLY); | |
if (in1 < 0) | |
error_file(open, argv[1]); | |
int64_t in2 = open(argv[2], O_RDONLY); | |
if (in2 < 0) | |
error_file(open, argv[2]); | |
int64_t out = STDOUT_FILENO; | |
if (argc == 4) | |
out = open(argv[3], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); | |
if (out < 0) | |
error_file(open, argv[3]); | |
struct stat s1; | |
fstat(in1, &s1); | |
uint8_t *m1 = mmap(NULL, s1.st_size, PROT_READ, MAP_SHARED, in1, 0); | |
if (m1 == MAP_FAILED) | |
error_file(mmap, argv[1]); | |
struct stat s2; | |
fstat(in2, &s2); | |
uint8_t *m2 = mmap(NULL, s2.st_size, PROT_READ, MAP_SHARED, in2, 0); | |
if (m2 == MAP_FAILED) | |
error_file(mmap, argv[2]); | |
size_t oz = s1.st_size < s2.st_size ? s1.st_size :s2.st_size; | |
ftruncate(out, oz); | |
uint8_t *mo = NULL; | |
if (out != STDOUT_FILENO) | |
if ((mo = mmap(NULL, oz, PROT_READ | PROT_WRITE, MAP_SHARED, out, 0)) == MAP_FAILED) | |
error_file(mmap, argv[3]); | |
for (size_t i = 0; i < oz; i++) | |
if (mo) | |
mo[i] = m1[i] ^ m2[i]; | |
else | |
putchar(m1[i] ^ m2[i]); | |
munmap(m1, s1.st_size); | |
munmap(m2, s2.st_size); | |
if (mo) | |
munmap(mo, oz); | |
if (out != STDOUT_FILENO) | |
close(out); | |
close(in2); | |
close(in1); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment