Skip to content

Instantly share code, notes, and snippets.

@cualquiercosa327
Forked from CTurt/main.c
Created January 13, 2021 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cualquiercosa327/e08e851ea2dba93cdfc0b1ed96f8c3ac to your computer and use it in GitHub Desktop.
Save cualquiercosa327/e08e851ea2dba93cdfc0b1ed96f8c3ac 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment