Skip to content

Instantly share code, notes, and snippets.

@CTurt

CTurt/main.c

Last active Jan 13, 2021
Embed
What would you like to do?
#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

This comment has been minimized.

Copy link
Owner Author

@CTurt 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