Skip to content

Instantly share code, notes, and snippets.

@CTurt
Last active January 13, 2021 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CTurt/b94b5c475f27003886ba to your computer and use it in GitHub Desktop.
Save CTurt/b94b5c475f27003886ba to your computer and use it in GitHub Desktop.
#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;
}
@CTurt
Copy link
Author

CTurt commented May 25, 2015

Combined my Exception library with my Preoop library. This is the most abstracted C code I have ever seen.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment