Implemented the file reading routine and added the skeleton for the interpreter.

This commit is contained in:
2022-02-07 19:25:08 +00:00
parent 00cad6336b
commit 8dbd655c43
2 changed files with 54 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
clox
+53
View File
@@ -0,0 +1,53 @@
#include <stdio.h>
#include <stdlib.h>
#include <sysexits.h>
#include <string.h>
#include <errno.h>
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");
}