From 1a847e6f3f1727571d6c185de52b418cc5746f4f Mon Sep 17 00:00:00 2001 From: metamuffin Date: Fri, 14 Jun 2024 22:45:22 +0200 Subject: can read file --- attocc.c | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 57 insertions(+), 16 deletions(-) diff --git a/attocc.c b/attocc.c index c18156c..9ff5ea4 100644 --- a/attocc.c +++ b/attocc.c @@ -1,6 +1,8 @@ +#include #include #include #include +#include #define NUM_KEYWORDS 32 static char *KEYWORDS[NUM_KEYWORDS] = { @@ -82,23 +84,15 @@ struct token *tokenize(char *source) { if (remaining >= 2) { if (p[0] == '/' && p[1] == '/') { p += 2; - while (*p) { - if (*p++ == '\n') { - break; - } - } + char c; + while ((c = *p++) && c != '\n') + ; continue; } else if (p[0] == '/' && p[1] == '*') { p += 2; - char last = '\0'; - while (*p) { - if (*p == '/' && last == '*') { - p++; - break; - } - last = *p; - p++; - } + char c, d; + while ((d = c, c = *p++) && c == '/' && d == '*') + ; continue; } } @@ -112,7 +106,7 @@ struct token *tokenize(char *source) { tokens = realloc(tokens, sizeof(struct token) * num_tokens); if (!tokens) { - fprintf(stderr, "realloc failed"); + fprintf(stderr, "realloc failed\n"); return NULL; } struct token *new_token = &tokens[num_tokens - 1]; @@ -131,4 +125,51 @@ struct token *tokenize(char *source) { return tokens; } -int main() {} +int main(int argc, char **argv) { + if (argc < 3) { + fprintf(stderr, "USAGE:\n\tattocc \n"); + return 1; + } + char *input = argv[1]; + char *output = argv[2]; + + int input_fd = open(input, O_RDONLY | O_CLOEXEC); + if (input_fd < 0) { + perror("cannot open input"); + return 1; + } + + int output_fd = open(output, O_WRONLY | O_TRUNC | O_CREAT | O_CLOEXEC, 0640); + if (output_fd < 0) { + perror("cannot open input"); + return 1; + } + + int source_len = 0; + char *source = NULL; + int size; + char buffer[4096]; + + while ((size = read(input_fd, &buffer, 4096))) { + if (size < 0) { + perror("cannot read source"); + return 1; + } + + source_len += size; + source = realloc(source, source_len + 1); + if (!source) { + fprintf(stderr, "malloc failed\n"); + return 1; + } + + for (int i = 0; i < size; i++) { + source[source_len - size + i] = buffer[i]; + } + } + source[source_len] = '\0'; + + printf("%s", source); + + return 0; +} -- cgit v1.2.3-70-g09d2