From 8dbd655c437937f0db2d046257ee4810f5a860a7 Mon Sep 17 00:00:00 2001 From: Garritt McCune Date: Mon, 7 Feb 2022 19:25:08 +0000 Subject: [PATCH] Implemented the file reading routine and added the skeleton for the interpreter. --- .gitignore | 1 + lox.c | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 lox.c diff --git a/.gitignore b/.gitignore index e69de29..e48d01a 100644 --- a/.gitignore +++ b/.gitignore @@ -0,0 +1 @@ +clox diff --git a/lox.c b/lox.c new file mode 100644 index 0000000..2c21d5b --- /dev/null +++ b/lox.c @@ -0,0 +1,53 @@ +#include +#include +#include +#include +#include + +void RunFile(const char*); +void RunPrompt(void); +char* GetFileContents(const char*); + +int main(int argc, char** argv) { + if (argc > 2) { + printf("Useage: clox [script]\n"); + exit(EX_USAGE); + } else if (argc == 2) { + RunFile(argv[1]); + } else { + RunPrompt(); + } +} + +void RunFile(const char* path) { + printf("Running '%s'\n", path); + char* contents = GetFileContents(path); + printf("%s", contents); +} + +char* GetFileContents(const char* path) { + FILE *script = fopen(path, "r"); + + if (!script) { + fprintf(stderr, "Failed to open script '%s'. %s.\n", path, strerror(errno)); + return NULL; + } + + size_t length; + char* content = NULL; + + size_t bytes_read = getdelim(&content, &length, '\0', script); + + fclose(script); + + if (bytes_read < 0) { + fprintf(stderr, "Failed to read '%s'. %s.\n", path, strerror(errno)); + return NULL; + } + + return content; +} + +void RunPrompt(void) { + printf("> \n"); +} \ No newline at end of file