Last active
January 13, 2021 22:33
-
-
Save CTurt/b94b5c475f27003886ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include "preoop.h" | |
#include "exception.h" | |
#define objects(a, b) objectList(a,\ | |
objectEntry(fileReader, b)\ | |
) | |
object(fileReader, | |
members { | |
FILE *handle; | |
size_t size; | |
char *buffer; | |
}; | |
fileReader *method(fileReader, init, char *filename) { | |
enum { | |
NO_ERROR, | |
ERROR_FOPEN, | |
ERROR_MALLOC, | |
errorCount, | |
}; | |
char *errors[errorCount] = { | |
[ERROR_FOPEN] = "Could not open file", | |
[ERROR_MALLOC] = "Could not allocate memory", | |
}; | |
try( | |
self->handle = fopen(filename, "rb"); | |
if(!self->handle) throw(ERROR_FOPEN); | |
fseek(self->handle, 0, SEEK_END); | |
self->size = ftell(self->handle); | |
self->buffer = malloc(self->size); | |
if(!self->buffer) throw(ERROR_MALLOC); | |
); | |
catch(ERROR_FOPEN || ERROR_MALLOC) { | |
printf("%s!\n", errors[e]); | |
free(self); | |
return NULL; | |
} | |
rewind(self->handle); | |
fread(self->buffer, self->size, 1, self->handle); | |
fclose(self->handle); | |
return self; | |
} | |
) | |
int main(void) { | |
fileReader *input = new(fileReader, "main.c"); | |
if(!input) return 0; | |
printf("%.*s\n", input->size, input->buffer); | |
free(input->buffer); | |
free(input); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Combined my Exception library with my Preoop library. This is the most abstracted C code I have ever seen.