Skip to content

Instantly share code, notes, and snippets.

@gcmurphy
Created December 18, 2013 22:35
Show Gist options
  • Save gcmurphy/8031057 to your computer and use it in GitHub Desktop.
Save gcmurphy/8031057 to your computer and use it in GitHub Desktop.
Things that I didn't know you could do with GNU C
#include <stdio.h>
#include <stdlib.h>
#define nil NULL
#define ScopedFile FILE * __attribute__((cleanup(fclosep)))
#define ScopedMemory void * __attribute__((cleanup(freep)))
void fclosep(FILE **f){
if (*f){
fclose(*f);
}
}
void freep(void **p){
if (*p){
free(*p);
*p = nil;
}
}
int main(){
ScopedFile f = nil;
ScopedMemory ptr = malloc(sizeof(long long));
if ((f = fopen("/tmp/foo.txt", "w")) != nil){
fprintf(f, "foo\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment