#define _POSIX_C_SOURCE 200809L
#include <unistd.h> /* read, write, close, lseek */
#include <fcntl.h> /* openat */
#include <stdlib.h> /* exit, strtoll, malloc */
#include <stdio.h> /* printf */
#include <errno.h> /* errno */
#include <err.h> /* NONPOSIX: err, errx */
/* Přečte soubor ‹file› a spočítá xor všech bajtů. Soubor čte skrze
* buffer, jehož velikost je zadána jako ‹bufsize›. */
int main( int argc, char** argv )
{
if ( argc < 3 )
errx( 1, "usage: %s file bufsize\n", argv[ 0 ] );
const char* filename = argv[ 1 ];
long long bufsize = strtoll( argv[ 2 ], 0, 0 );
char* buf = ( char* )malloc( bufsize );
if ( !buf ) err( 1, "malloc" );
int fd = openat( AT_FDCWD, filename, O_RDONLY );
if ( fd == -1 )
err( 1, "openat %s", filename );
unsigned char result = 0;
int bytes;
while ( ( bytes = read( fd, buf, bufsize ) ) > 0 )
{
for ( long long i = 0; i < bufsize; ++i )
{
result ^= buf[ i ];
}
}
if ( bytes == -1 )
err( 1, "read stdin" );
printf( "0x%02hhx\n", result );
if ( close( fd ) ) warn( "close %s", filename );
free( buf );
return 0;
}