Skip to content

Instantly share code, notes, and snippets.

@ariscop
Created September 27, 2018 02:25
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 ariscop/842252b7c2afb7d5bbedb46ed7bd258e to your computer and use it in GitHub Desktop.
Save ariscop/842252b7c2afb7d5bbedb46ed7bd258e to your computer and use it in GitHub Desktop.
with macro in c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define with(_init, _fini) for(int _count = ((_init), 1); _count--; (_fini))
#define with_file(var, name, access) with(var = fopen(name, access), (var ? fclose(var) : 0 ))
void
test_macro(char *file)
{
FILE *fp;
with_file(fp, file, "rb") {
if(!fp)
printf("Error opening %s: %s\n", file, strerror(errno));
else
printf("Opened file %s\n", file);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment