2010-07-20

Silly C hacks

Macros! To do safe mallocs and fopens! Brittle like the glass you tread upon!

/* A small cat that prints out the files given to it */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <sys/stat.h>

#define BLOCK(pre, post, ok, error, block) \
{ \
pre; \
if (ok) { \
block; \
post; \
} else { \
error; \
} \
}

#define with_malloc(t, var, sz, block) \
BLOCK(t var = (t)malloc(sz), free(var), var, \
fprintf(stderr, "Malloc failed, out of memory\n"); exit(1), block)

#define with_file(var, fn, mode, error, block) \
BLOCK(FILE* var = fopen(fn, mode), fclose(var), var, error, block)

#define with_file_contents(var, len, fn, error, block) \
with_file(var##__f, fn, "r", error, \
off_t len = file_size(fn); \
with_malloc(char*, var, len+1, \
len = fread(var, 1, len, var##__f); \
var[len] = 0; \
block))

off_t file_size(char *path)
{
struct stat st;
stat(path, &st);
return st.st_size;
}

int main(int argc, char *argv[]) {
int i;
for (i=1; i<argc; i++) {
with_file_contents(s, slen, argv[i], fprintf(stderr, "Couldn't open %s.\n", argv[i]),
fwrite(s, 1, slen, stdout);
);
}
}



It would be kinda fun to port the whole functional array-munging part of prelude.ml to C. Fun in a very painful fashion.
Post a Comment