diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/kat.c | 23 | ||||
-rw-r--r-- | src/util/map.c | 39 | ||||
-rw-r--r-- | src/util/map.h | 10 |
3 files changed, 55 insertions, 17 deletions
@@ -6,6 +6,8 @@ #include <sys/stat.h> #include <unistd.h> +#include "util/map.h" + int entry_kat(int argc, char **argv) { if (argc == 2 && strcmp(argv[1], "-h") == 0) { fprintf(stderr, "Gebruik: kat [BESTAND]...\n" @@ -16,26 +18,13 @@ int entry_kat(int argc, char **argv) { for (int i = 1; i < argc; i++) { const char *fname = argv[i]; - int fd = open(fname, O_RDONLY); - - struct stat sb; - if (fstat(fd, &sb) == -1) { - fprintf(stderr, "Kon bestand niet lezen\n"); - return 0; - } - - char *addr = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd, 0); - if (addr == MAP_FAILED) { - fprintf(stderr, "Kon bestand niet kaarten\n"); - return 0; - } + struct map *map = open_map(fname); - for (size_t i = 0; i < sb.st_size; i++) { - putchar(addr[i]); + for (size_t i = 0; i < map->sb.st_size; i++) { + putchar(map->addr[i]); } - munmap(addr, sb.st_size); - close(fd); + close_map(map); } return 0; diff --git a/src/util/map.c b/src/util/map.c new file mode 100644 index 0000000..db691d3 --- /dev/null +++ b/src/util/map.c @@ -0,0 +1,39 @@ +#include <fcntl.h> +#include <stdio.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/mman.h> +#include <sys/stat.h> +#include <unistd.h> + +#include "map.h" + +struct map *open_map(const char *fname) { + int fd = open(fname, O_RDONLY); + + struct stat sb; + if (fstat(fd, &sb) == -1) { + fprintf(stderr, "Kon bestand niet lezen\n"); + return NULL; + } + + char *addr = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd, 0); + if (addr == MAP_FAILED) { + fprintf(stderr, "Kon bestand niet kaarten\n"); + return NULL; + } + + struct map *res = calloc(1, sizeof(struct map)); + + res->addr = addr; + res->sb = sb; + res->fd = fd; + return res; +} + +void close_map(struct map *m) { + munmap(m->addr, m->sb.st_size); + close(m->fd); + free(m); +} diff --git a/src/util/map.h b/src/util/map.h new file mode 100644 index 0000000..232720f --- /dev/null +++ b/src/util/map.h @@ -0,0 +1,10 @@ +#include <sys/stat.h> + +struct map { + char *addr; + struct stat sb; + int fd; +}; + +struct map *open_map(const char *fname); +void close_map(struct map *m); |