summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/tak.c74
-rw-r--r--src/util/map.c4
2 files changed, 53 insertions, 25 deletions
diff --git a/src/tak.c b/src/tak.c
index ead1038..d92123a 100644
--- a/src/tak.c
+++ b/src/tak.c
@@ -74,13 +74,13 @@ static void process(struct state state) {
return NULL; \
}
-static char *read_stdin(size_t *sz) {
+static char *read_stream(FILE *stream, size_t *sz) {
*sz = 0;
size_t cap = 4096;
char *res = malloc(cap);
CHECK_OOM(res);
- while (!feof(stdin)) {
+ while (!feof(stream)) {
if (cap-*sz == 0) {
cap *= 2;
res = realloc(res, cap);
@@ -88,10 +88,10 @@ static char *read_stdin(size_t *sz) {
}
const size_t amount = cap-*sz;
- const size_t n = fread(res+*sz, 1, amount, stdin);
+ const size_t n = fread(res+*sz, 1, amount, stream);
*sz += n;
- if (n != amount && !feof(stdin)) {
+ if (n != amount && !feof(stream)) {
fprintf(stderr, "tak: fout tijdens lezen van standaard invoer.\n");
free(res);
return NULL;
@@ -101,32 +101,60 @@ static char *read_stdin(size_t *sz) {
return res;
}
+int handleStream(FILE *stream) {
+ size_t sz = 0;
+ char *data = read_stream(stream, &sz);
+ if (data == NULL) {
+ return 1;
+ }
+
+ struct state state = { .buf = data, .sz = sz };
+ process(state);
+
+ free(data);
+ return 0;
+}
+
+int handleFile(char *fname) {
+ struct map *map = open_map(fname);
+ if (map == NULL) {
+ return 1;
+ }
+
+ struct state state = { .buf = map->addr, .sz = map->sb.st_size };
+ process(state);
+
+ close_map(map);
+
+ return 0;
+}
+
int entry_tak(int argc, char **argv) {
char **args = parse_options(argc, argv);
- if (*args == NULL) {
- size_t sz = 0;
- char *data = read_stdin(&sz);
- if (data == NULL) {
- return 1;
- }
- struct state state = { .buf = data, .sz = sz };
- process(state);
+ if (*args == NULL) {
+ handleStream(stdin);
+ return 0;
+ }
- free(data);
- } else {
- while (*args != NULL) {
- struct map *map = open_map(*args);
- if (map == NULL) {
- return 1;
- }
+ while (*args != NULL) {
+ if (!strcmp(*args, "-")) {
+ handleStream(stdin);
+ goto next;
+ }
- struct state state = { .buf = map->addr, .sz = map->sb.st_size };
- process(state);
+ if (!handleFile(*args)) {
+ goto next;
+ }
- close_map(map);
- args++;
+ FILE *stream = fopen(*args, "rb");
+ if (handleStream(stream)) {
+ return 1;
}
+ fclose(stream);
+
+next:
+ args++;
}
return 0;
diff --git a/src/util/map.c b/src/util/map.c
index cd2da42..27e1c04 100644
--- a/src/util/map.c
+++ b/src/util/map.c
@@ -14,13 +14,13 @@ struct map *open_map(const char *fname) {
struct stat sb;
if (fstat(fd, &sb) == -1) {
- fprintf(stderr, "Kon bestand niet lezen\n");
+ //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 projecteren in geheugen\n");
+ //fprintf(stderr, "Kon bestand niet projecteren in geheugen\n");
return NULL;
}