art with code


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; \

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 to C. Fun in a very painful fashion.
Post a Comment

About Me

My Photo

Built art installations, web sites, graphics libraries, web browsers, mobile apps, desktop apps, media player themes, many nutty prototypes, much bad code, much bad art.

Have freelanced for Verizon, Google, Mozilla, Warner Bros, Sony Pictures, Yahoo!, Microsoft, Valve Software, TDK Electronics.

Ex-Chrome Developer Relations.