Implemented the file reading routine and added the skeleton for the interpreter.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
clox
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
Reference in New Issue
Block a user