scratch/misc/mmap-file.c
2024-12-26 14:02:40 -03:00

55 lines
1.1 KiB
C

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/auxv.h>
#include <unistd.h>
#include <fcntl.h>
#include <err.h>
int main(int argc, char **argv)
{
if (argc < 2)
errx(EXIT_FAILURE, "expected file name");
const char *filename = argv[1];
int fd = open(filename, O_RDONLY);
if (fd < 0)
err(EXIT_FAILURE, "open");
struct stat fst = {0};
if (fstat(fd, &fst) < 0)
err(EXIT_FAILURE, "fstat");
const size_t filesize = fst.st_size;
uint8_t *filem = mmap(NULL, filesize, PROT_READ, MAP_PRIVATE, fd, 0);
if (filem == MAP_FAILED)
err(EXIT_FAILURE, "mmap failed");
/* we can close the descriptor now */
close(fd);
unsigned int seed = 0;
memcpy(&seed, (void *)getauxval(AT_RANDOM), sizeof(seed));
srand(seed);
const size_t off = abs(rand()) % filesize;
uint8_t pb = 0, cb;
size_t cbo = 0;
for (size_t i = off; i < off + 0xff && i < filesize; ++i) {
cb = filem[i];
if (cb == pb)
++cbo;
if (cbo == 16) {
printf("* ");
cbo = 0;
} else
printf("%x ", cb);
pb = cb;
}
putchar('\n');
munmap(filem, filesize);
return 0;
}