Skip to content

Instantly share code, notes, and snippets.

@vurtun
Last active July 1, 2022 10:01
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 vurtun/07275bd0a511aa9e9a040cc2230fa983 to your computer and use it in GitHub Desktop.
Save vurtun/07275bd0a511aa9e9a040cc2230fa983 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#define xglue(x, y) x##y
#define glue(x, y) xglue(x, y)
#define uniqid(name) glue(name, __LINE__)
#define scp_brk(name) goto xglue(___SCOPE___,name)
#define scp_file(name,f,p,fmt)\
xglue(___SCOPE___,name): for(int uniqid(_i_) = (f) ? 1 : ((((f) = fopen(p,fmt)) == 0) ? 1 : 0);\
(uniqid(_i_) == 0) ? 1 : ((f) ? (fclose(f), 0): 0); ++uniqid(_i_))
extern int
main(int argc, char **argv) {
FILE *fp = 0;
scp_file(s0, fp, argv[1], "r") {
char buf[1024];
fread(buf, sizeof(char), 1024, fp);
if (buf[0] == 0) {
scp_brk(s0); // works correctly
}
for (int i = 0; i < 1024; ++i) {
printf("%d\n", i);
if (i == argc) {
scp_brk(s0); // works correctly
}
}
if (buf[1] == 1) {
return 0; // will leak file handle
}
printf("%s\n", buf);
}
if(!fp) {
printf("failed to open file: %s\n", argv[1]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment